Golang Concurrency Goroutines Quiz

Golang
0 Passed
0% acceptance

40 comprehensive questions on Golang goroutines, covering goroutine creation, spawning, stack management, leaks, and best practices — with 18 code examples demonstrating concurrent programming patterns and common pitfalls.

40 Questions
~80 minutes
1

Question 1

What is a goroutine in Golang?

A
A lightweight thread managed by the Go runtime
B
A heavy operating system thread
C
A function that runs synchronously
D
A type of channel
2

Question 2

How do you create a goroutine?

go
go func() {
    fmt.Println("Hello from goroutine")
}()
A
Prefix any function call with 'go'
B
Use goroutine keyword
C
Call runtime.Goroutine()
D
Use thread.New()
3

Question 3

What happens when the main function ends in a Go program?

go
package main

import "fmt"

func main() {
    go func() {
        fmt.Println("This might not print")
    }()
    // main ends here
}
A
The program exits immediately, possibly before goroutines finish
B
All goroutines finish before program exits
C
Compilation error
D
Runtime panic
4

Question 4

What is the initial stack size of a goroutine?

A
About 2KB, growing dynamically as needed
B
8MB like OS threads
C
Fixed size that never changes
D
Same as the main stack
5

Question 5

How do goroutines communicate?

A
Through channels
B
Through shared memory
C
Through global variables
D
Direct function calls
6

Question 6

What is a goroutine leak?

A
A goroutine that never exits, consuming memory indefinitely
B
A goroutine that panics
C
A goroutine that runs too fast
D
A goroutine that blocks forever
7

Question 7

How can you prevent goroutine leaks?

go
go func() {
    defer func() { /* cleanup */ }()
    for {
        select {
        case <-done:
            return
        default:
            // do work
        }
    }
}()
A
Use done channels or contexts to signal goroutines to exit
B
Use runtime.GC()
C
Set GOMAXPROCS to 1
D
Cannot prevent leaks
8

Question 8

What is the GOMAXPROCS setting?

A
Maximum number of OS threads that can execute Go code simultaneously
B
Maximum number of goroutines allowed
C
Maximum stack size per goroutine
D
Maximum heap size
9

Question 9

How do you pass data to a goroutine?

go
func worker(data string) {
    fmt.Println(data)
}

func main() {
    go worker("hello")
}
A
Through function parameters
B
Through global variables
C
Through shared memory
D
Cannot pass data
10

Question 10

What happens when you modify a shared variable from multiple goroutines?

go
var counter int
go func() { counter++ }()
go func() { counter++ }()
A
Race condition - unpredictable results
B
Always works correctly
C
Compilation error
D
Runtime panic
11

Question 11

What is the difference between goroutines and OS threads?

A
Goroutines are lighter weight and managed by Go runtime
B
OS threads are lighter weight
C
No difference
D
Goroutines are slower
12

Question 12

How do you wait for a goroutine to finish?

go
var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    // do work
}()
wg.Wait()
A
Use sync.WaitGroup
B
Use time.Sleep
C
Use runtime.Goexit
D
Cannot wait for goroutines
13

Question 13

What is stack splitting in goroutines?

A
When a goroutine's stack grows, it can be moved to a new larger stack
B
When a goroutine is paused
C
When a goroutine panics
D
When a goroutine blocks
14

Question 14

How do you handle panics in goroutines?

go
go func() {
    defer func() {
        if r := recover(); r != nil {
            // handle panic
        }
    }()
    // risky code
}()
A
Use recover() in a deferred function
B
Panics in goroutines crash the program
C
Use try-catch
D
Cannot handle panics in goroutines
15

Question 15

What is the runtime.Gosched() function?

A
Yields the processor to other goroutines
B
Creates a new goroutine
C
Sleeps for a duration
D
Exits the current goroutine
16

Question 16

How do you limit the number of concurrent goroutines?

go
semaphore := make(chan struct{}, maxGoroutines)
for i := 0; i < n; i++ {
    go func() {
        semaphore <- struct{}{}  // acquire
        defer func() { <-semaphore }()  // release
        // do work
    }()
}
A
Use a buffered channel as a semaphore
B
Use GOMAXPROCS
C
Use sync.Mutex
D
Cannot limit goroutines
17

Question 17

What is a goroutine's lifecycle?

A
Created with go, runs until function returns or panics
B
Created with go, runs forever
C
Same as main function
D
Depends on GOMAXPROCS
18

Question 18

How do you get the number of currently running goroutines?

go
import "runtime"

goroutines := runtime.NumGoroutine()
A
runtime.NumGoroutine()
B
Use sync.WaitGroup
C
Check GOMAXPROCS
D
Cannot get the count
19

Question 19

What happens when a goroutine calls runtime.Goexit()?

A
The current goroutine exits immediately
B
All goroutines exit
C
The program panics
D
Nothing happens
20

Question 20

How do you implement a worker pool pattern?

go
func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        results <- j * 2
    }
}

func main() {
    jobs := make(chan int, 100)
    results := make(chan int, 100)
    
    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }
    
    for j := 1; j <= 5; j++ {
        jobs <- j
    }
    close(jobs)
    
    for a := 1; a <= 5; a++ {
        <-results
    }
}
A
Create multiple goroutines reading from a jobs channel and writing to results channel
B
Use a single goroutine
C
Use global variables
D
Use sync.Mutex
21

Question 21

What is the problem with this code?

go
for i := 0; i < 10; i++ {
    go func() {
        fmt.Println(i)
    }()
}
A
All goroutines capture the same variable i, printing 10 ten times
B
Compilation error
C
Race condition
D
No problem
22

Question 22

How do you fix the loop variable capture issue?

go
for i := 0; i < 10; i++ {
    go func(i int) {
        fmt.Println(i)
    }(i)
}
A
Pass the variable as a parameter to the goroutine function
B
Use global variables
C
Use sync.Mutex
D
Cannot fix
23

Question 23

What is cooperative scheduling in Go?

A
Goroutines yield control at I/O operations and channel communications
B
Goroutines are preemptively scheduled by the OS
C
Goroutines run to completion
D
No scheduling in Go
24

Question 24

How do you detect goroutine leaks in testing?

go
func TestNoLeak(t *testing.T) {
    before := runtime.NumGoroutine()
    // test code that spawns goroutines
    time.Sleep(100 * time.Millisecond)  // wait for cleanup
    after := runtime.NumGoroutine()
    if after > before {
        t.Errorf("Goroutine leak: %d before, %d after", before, after)
    }
}
A
Check runtime.NumGoroutine() before and after the test
B
Use pprof
C
Use sync.WaitGroup
D
Cannot detect leaks
25

Question 25

What is the maximum number of goroutines you can create?

A
Limited by available memory
B
Fixed at 1000
C
Same as GOMAXPROCS
D
Limited by CPU cores
26

Question 26

How do you implement a timeout for a goroutine?

go
select {
case result := <-ch:
    // use result
case <-time.After(5 * time.Second):
    // timeout
}
A
Use select with time.After channel
B
Use time.Sleep
C
Use runtime.Goexit
D
Cannot timeout goroutines
27

Question 27

What is the difference between buffered and unbuffered channels in goroutines?

A
Buffered channels allow sending without immediate receiver
B
No difference for goroutines
C
Buffered channels are faster
D
Unbuffered channels don't work with goroutines
28

Question 28

How do you gracefully shutdown multiple goroutines?

go
done := make(chan struct{})
for i := 0; i < n; i++ {
    go worker(done)
}
// To shutdown:
close(done)
A
Use a done channel that goroutines select on
B
Use runtime.Goexit
C
Use os.Exit
D
Cannot shutdown gracefully
29

Question 29

What is fan-out pattern in goroutines?

A
Multiple goroutines reading from the same channel
B
One goroutine writing to multiple channels
C
Goroutines calling each other
D
No such pattern
30

Question 30

What is fan-in pattern?

A
Multiple goroutines sending to the same channel
B
One goroutine reading from multiple channels
C
Goroutines merging results
D
All of the above
31

Question 31

How do you implement fan-in?

go
func fanIn(ch1, ch2 <-chan int) <-chan int {
    c := make(chan int)
    go func() { for { c <- <-ch1 } }()
    go func() { for { c <- <-ch2 } }()
    return c
}
A
Create goroutines that forward from multiple input channels to one output channel
B
Use select statement
C
Use sync.WaitGroup
D
Cannot implement fan-in
32

Question 32

What is the problem with too many goroutines?

A
Memory usage and scheduling overhead
B
Too slow execution
C
Compilation errors
D
No problems
33

Question 33

How do you debug deadlocks in goroutines?

A
Use go run -race, check for deadlock detection
B
Use pprof
C
Use runtime.NumGoroutine
D
Cannot debug deadlocks
34

Question 34

What is a context in goroutine management?

A
A way to carry deadlines, cancellation signals, and request-scoped values
B
A replacement for channels
C
A type of goroutine
D
A debugging tool
35

Question 35

How do you use context for goroutine cancellation?

go
ctx, cancel := context.WithCancel(context.Background())
go func() {
    select {
    case <-ctx.Done():
        return
    default:
        // do work
    }
}()
// Later: cancel()
A
Create cancellable context and select on ctx.Done()
B
Use time.After
C
Use runtime.Goexit
D
Cannot cancel goroutines
36

Question 36

What is the best practice for error handling in goroutines?

go
results := make(chan result, n)
for i := 0; i < n; i++ {
    go func() {
        res, err := doWork()
        results <- result{res, err}
    }()
}
// Collect results and handle errors
A
Return errors through channels along with results
B
Panic in goroutines
C
Ignore errors
D
Use global error variables
37

Question 37

How do you implement a pipeline with goroutines?

go
func generator() <-chan int {
    ch := make(chan int)
    go func() {
        for i := 0; i < 10; i++ {
            ch <- i
        }
        close(ch)
    }()
    return ch
}

func main() {
    for num := range generator() {
        fmt.Println(num)
    }
}
A
Each stage is a goroutine that reads from input channel and writes to output channel
B
Use global variables
C
Use arrays
D
Cannot implement pipelines
38

Question 38

What is the GODEBUG environment variable used for?

A
Enabling debug output for goroutine scheduling and GC
B
Setting GOMAXPROCS
C
Debugging race conditions
D
Profiling memory usage
39

Question 39

How do you avoid goroutine leaks in HTTP servers?

go
func handler(w http.ResponseWriter, r *http.Request) {
    done := make(chan struct{})
    go func() {
        defer close(done)
        // long running work
    }()
    select {
    case <-done:
        // work completed
    case <-r.Context().Done():
        // request cancelled
        return
    }
}
A
Use request context to cancel goroutines when client disconnects
B
Use time.Sleep
C
Ignore client disconnections
D
Cannot avoid leaks in HTTP
40

Question 40

What is the most important principle for goroutine usage?

A
Always ensure goroutines can exit, prefer channels over shared memory
B
Create as many goroutines as possible
C
Use goroutines for all functions
D
Avoid channels for performance

QUIZZES IN Golang