Search⌘ K

Puzzle 18 Explanation: Go Job

Explore the Go Job puzzle to understand how using pointer versus value types in channels affects concurrency and data consistency. Learn to identify issues with copying structs in goroutines and discover the solution by using pointer channels for correct state management.

We'll cover the following...

Try it yourself

Try executing the code below to see the result for yourself.

Go (1.16.5)
package main
import (
"fmt"
)
type Job struct {
State string
done chan struct{}
}
func (j *Job) Wait() {
<-j.done
}
func (j *Job) Done() {
j.State = "done"
close(j.done)
}
func main() {
ch := make(chan Job)
go func() {
j := <-ch
j.Done()
}()
job := Job{"ready", make(chan struct{})}
ch <- job
job.Wait()
fmt.Println(job.State)
}

Explanation

At first glance, the code looks fine. We’re using a pointer receiver in the Job struct ...