CodeBlanks Logo Icon CodeBlanks

Number of goroutines

Learn to launch many goroutines and concurrency.

Many goroutines

Starting many goroutines in Go is easy: write go f(i) in a loop. Each runs independently and the scheduler spreads them across cores.

Hundreds of thousands of goroutines can live at once; the memory cost is in kilobytes. This is the key trait that separates goroutines from OS threads.

But if goroutines access shared data a data race occurs. You must protect it with sync.Mutex or a channel. go test -race detects races.

Goroutine cost

A goroutine starts with about 2 KB of stack. When it fills Go doubles it automatically (growing stack). This avoids memory issues even with deep recursion.

Comparison: a Linux thread reserves 8 MB of stack. 100k threads need 800 GB; 100k goroutines run with about 200 MB.

This efficiency makes Go a top choice for concurrent server programs.

Practice Launch many goroutines

Inside main, add a go work() call inside a loop and print many started with fmt.Println.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func work() {
    fmt.Println("çoklu başladı")
}

func main() {
    for i := 0; i < 3; i++ {
        go work()
    }
    fmt.Println("çoklu başladı")
}

Expected output

çoklu başladı

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is a data race detected?

  • go run -v
  • go vet
  • go build -race
  • go test -race Correct answer

Explanation: go vet does static analysis, not race detection.

2 Goroutine stack size

Question
A goroutine starts with about ____ of stack.
Answer
A goroutine starts with about 2 KB of stack.

Explanation: 8 MB is for OS threads.

3 Match cost concepts

Term Meaning
goroutine 2 KB
OS thread 8 MB
growing stack Auto-grows
data race Race

All lessons in Intermediate