Bird
Raised Fist0
Goprogramming~10 mins

Goroutine creation - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Goroutine creation
Start main function
↓
Create goroutine
↓
Goroutine runs concurrently
↓
Main continues execution
↓
Wait or finish main
↓
Program ends
The main function starts, creates a goroutine that runs concurrently, then continues. The program ends when main finishes.
Execution Sample
Go
package main
import "fmt"
func sayHello() {
    fmt.Println("Hello from goroutine")
}
func main() {
    go sayHello()
    fmt.Println("Hello from main")
}
This code creates a goroutine to run sayHello concurrently while main prints its own message.
Execution Table
StepActionEvaluationResult
1Start main functionmain startsReady to run code
2Create goroutine with go sayHello()sayHello scheduledsayHello runs concurrently
3Execute fmt.Println("Hello from main")Print main messageOutput: Hello from main
4Goroutine runs sayHello()Print goroutine messageOutput: Hello from goroutine
5Main function endsProgram endsProgram terminates
💡 Main function ends, program terminates, goroutine may finish before or after main prints
Variable Tracker
VariableStartAfter goroutine creationAfter main printFinal
sayHello goroutineNot startedScheduled to runRunning or finishedFinished
main functionRunningRunningRunningFinished
Key Moments - 2 Insights
Why might the goroutine's print appear before or after the main print?
Because goroutines run concurrently, their execution order is not guaranteed. See execution_table steps 3 and 4 where outputs can appear in any order.
What happens if main ends before the goroutine runs?
The program ends immediately, stopping all goroutines. So the goroutine might not print if main finishes too soon, as shown in execution_table step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed at step 3?
AHello from goroutine
BHello from main
CNo output
DProgram ends
💡 Hint
Check the 'Result' column at step 3 in execution_table
At which step does the goroutine start running?
AStep 1
BStep 2
CStep 4
DStep 3
💡 Hint
Look for when sayHello prints in execution_table
If main ends immediately after creating the goroutine, what might happen?
AGoroutine might not run at all
BGoroutine definitely prints first
CProgram waits for goroutine to finish
DMain prints twice
💡 Hint
See key_moments about program ending before goroutine runs
Concept Snapshot
Goroutine creation in Go:
- Use 'go' keyword before a function call
- Starts function concurrently
- Main continues without waiting
- Program ends when main finishes
- Goroutine may not complete if main ends early
Full Transcript
This example shows how a goroutine is created in Go using the 'go' keyword before a function call. The main function starts and creates a goroutine that runs the sayHello function concurrently. The main function then prints its own message. Because goroutines run at the same time as main, their output order can vary. If main ends before the goroutine runs, the program stops immediately and the goroutine may not print. This trace shows each step: starting main, creating the goroutine, printing from main, printing from the goroutine, and ending the program.

Practice

(1/5)
1. What does adding go before a function call do in Go?
easy
A. Starts the function as a new goroutine running concurrently
B. Delays the function call until later
C. Runs the function only if a condition is true
D. Converts the function into a method

Solution

  1. Step 1: Understand the role of go keyword

    The go keyword in Go is used to start a new goroutine, which is a lightweight thread that runs concurrently with other goroutines.
  2. Step 2: Identify what happens when go is used before a function call

    When go is placed before a function call, that function runs asynchronously, allowing the program to continue without waiting for it to finish.
  3. Final Answer:

    Starts the function as a new goroutine running concurrently -> Option A
  4. Quick Check:

    go starts concurrent execution [OK]
Hint: Remember: 'go' runs function concurrently [OK]
Common Mistakes:
  • Thinking 'go' delays function execution
  • Confusing goroutine with method conversion
  • Assuming 'go' runs function conditionally
2. Which of the following is the correct syntax to start a goroutine that calls function doWork()?
easy
A. run go doWork()
B. go doWork()
C. start doWork()
D. goroutine doWork()

Solution

  1. Step 1: Recall the syntax for starting a goroutine

    In Go, to start a goroutine, you simply write go followed by the function call without parentheses or extra keywords.
  2. Step 2: Match the correct syntax

    go doWork() uses go doWork(), which is the exact syntax to start a goroutine. Other options use invalid keywords or extra words.
  3. Final Answer:

    go doWork() -> Option B
  4. Quick Check:

    Correct goroutine syntax = go function() [OK]
Hint: Use 'go' directly before function call [OK]
Common Mistakes:
  • Adding extra keywords like 'start' or 'run'
  • Writing 'goroutine' instead of 'go'
  • Missing parentheses after function name
3. What will be the output of this Go program?
package main
import (
  "fmt"
  "time"
)
func sayHello() {
  fmt.Println("Hello from goroutine")
}
func main() {
  go sayHello()
  fmt.Println("Hello from main")
  time.Sleep(100 * time.Millisecond)
}
medium
A. Hello from main\nHello from goroutine
B. Hello from goroutine\nHello from main
C. Hello from main only
D. No output

Solution

  1. Step 1: Understand goroutine and main execution order

    The sayHello function runs as a goroutine, so it runs concurrently with the main function. The main function prints first, then sleeps to allow the goroutine to run.
  2. Step 2: Analyze output order

    Main prints "Hello from main" immediately. The goroutine prints "Hello from goroutine" during the sleep period, so both lines appear with main's message first.
  3. Final Answer:

    Hello from main Hello from goroutine -> Option A
  4. Quick Check:

    main prints first, goroutine runs during sleep [OK]
Hint: Sleep to let goroutine print after main [OK]
Common Mistakes:
  • Assuming goroutine always prints first
  • Forgetting to add sleep to wait for goroutine
  • Expecting no output because goroutine is async
4. Identify the error in this Go code snippet that tries to start a goroutine:
func printNumber(n int) {
  fmt.Println(n)
}

func main() {
  go printNumber
}
medium
A. Goroutines cannot take parameters
B. Function printNumber cannot be used as goroutine
C. Missing parentheses after function name in goroutine call
D. Missing import of fmt package

Solution

  1. Step 1: Check goroutine syntax for function calls

    When starting a goroutine, the function must be called with parentheses, even if it has parameters. Here, go printNumber misses parentheses and argument.
  2. Step 2: Identify the specific syntax error

    The code should be go printNumber(5) or some integer argument with parentheses to call the function properly as a goroutine.
  3. Final Answer:

    Missing parentheses after function name in goroutine call -> Option C
  4. Quick Check:

    Function call needs parentheses [OK]
Hint: Always use parentheses with goroutine function calls [OK]
Common Mistakes:
  • Omitting parentheses when calling function as goroutine
  • Thinking goroutines can't have parameters
  • Ignoring missing imports causing unrelated errors
5. You want to start 3 goroutines that each print their number (1, 2, 3). Which code correctly ensures each goroutine prints its own number without all printing 4?
for i := 1; i <= 3; i++ {
  go func() {
    fmt.Println(i)
  }()
}
hard
A. Add time.Sleep inside the loop after starting goroutine
B. Use global variable instead of loop variable
C. Remove the anonymous function and call go fmt.Println(i)
D. Pass i as parameter to anonymous function: go func(n int) { fmt.Println(n) }(i)

Solution

  1. Step 1: Understand closure capturing loop variable

    The anonymous function captures the variable i by reference, so all goroutines print the final value (4) after the loop ends.
  2. Step 2: Fix by passing loop variable as parameter

    Passing i as a parameter to the anonymous function creates a new local copy for each goroutine, preserving the correct value.
  3. Final Answer:

    Pass i as parameter to anonymous function: go func(n int) { fmt.Println(n) }(i) -> Option D
  4. Quick Check:

    Pass loop variable as argument to fix closure [OK]
Hint: Pass loop variable as argument to goroutine function [OK]
Common Mistakes:
  • Not passing loop variable, causing all goroutines to print same value
  • Using global variables instead of parameters
  • Relying on sleep to fix output order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard