Mastering Concurrency in Go Synchronizing Critical Sections With Mutex (Part 3)

Part 1 , Part 2 , Part 3 , Part 4 , Part 5 In Go, critical sections refer to parts of your code that manipulate a resource which must be accessed by only one goroutine at a time. By using a mutex, you can temporarily lock a critical section, perform the operation, and then unlock it, allowing other goroutines to access the resource. Attempting to lock a critical section in a goroutine will block execution until the lock can be acquired. ...

Mastering Concurrency in Go: Fan in With Channels (Part 2)

Part 1 , Part 2 , Part 3 , Part 4 , Part 5 Return values from go routines cannot be captured in the usual way with the = operator because starting a go routine is non blocking. A channel can be used to collect the results from many concurrent go routines. Write a value to a channel inside the go routine that is doing the work, then in main() read from the channel until it is closed to collect all the results from the go routines. ...

Mastering Concurrency in Go: With Fanout and Goroutines (Part 1)

Part 1 , Part 2 , Part 3 , Part 4 , Part 5 Goroutines can be used to take advantage of CPUs with multiple processors. Starting a Goroutine using the “go” keyword, will start execution on a thread in parallel if a thread is available. You will need to make sure that your main function does not exit before all the goroutines finish their work. Playground: https://go.dev/play/p/FTJLzwY34l2 package main import ( "fmt" "sync" ) func main() { wg := sync.WaitGroup{} // use many goroutines to compute the product of two numbers for i := 0; i < 100; i++ { for j := 0; j < 100; j++ { // capture the value of i and j // otherwise, the value of i and j will be changed // before the goroutine is executed i := i j := j // add a goroutine to the wait group wg.Add(1) go func() { // defer the decrement of the wait group defer wg.Done() // compute the product product := i * j // print the product fmt.Println(i, j, product) }() } } // ensure that goroutines are executed // otherwise, the program will exit // before all the goroutines are executed wg.Wait() fmt.Println("Done") }