Advertisement
In the previous blog, we learned about Golang Goroutine Syntax and Golang Goroutine Waitgroup. Waitgroups helped us to synchronize Goroutines but it failed to synchronize multiple goroutines. In this blog, we will learn about Golang Goroutine Mutex which will help us to Synchronize multiple Goroutines.
Golang Goroutine Mutex
Mutex in Golang helps us to put a lock and unlock certain functions. In this example, we have a ReadWriteMutex from the Golang sync package.
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup = sync.WaitGroup{}
var ct int = 0
var m sync.RWMutex = sync.RWMutex{}
func hello() {
fmt.Printf("Hello Go %v\n", ct)
m.RUnlock()
wg.Done()
}
func counter() {
ct++
m.Unlock()
wg.Done()
}
func main() {
runtime.GOMAXPROCS(11)
for i := 0; i < 5; i++ {
wg.Add(2)
m.RLock()
go hello()
m.Lock()
go counter()
}
wg.Wait()
}
Hello Go 0
Hello Go 1
Hello Go 2
Hello Go 3
Hello Go 4
From the Previous example, we know that the hello function is just a Read Function as it doesn’t change any value and the counter function is a Write function as it increments the counter value in every call.
In order to synchronize the goroutines, we will have to synchronize the Writing part (counter function) to the Reading Part (hello function).
We can put Locks and Unlock it when the function call’s execution is done.
RLock() and RUnlock() mutex functions for locking and unlocking reading functions.
Lock() and Unlock() mutex functions for locking and unlocking writing functions.
runtime.GOMAXPROCS(11)
This statement in line 27, sets a number of threads to 11 and we need total of 10 threads for the execution of goroutines (1 extra is taken for safety purposes).
Concurrency in Golang was introduced to make programs efficient and fast. But, this makes our program synchronous, and thus slow, and concurrency hasn’t been effective.
Way to make Concurrency effective using Mutex in Golang.
Golang GOMAXPROCS
GOMAXPROCS function sets the maximum number of CPUs that will be executing simultaneously.
When the passed value in GOMAXPROCS is less than 1, it doesn’t set the number of CPUs but returns the current setting.
fmt.Printf("Number of threads : %v\n", runtime.GOMAXPROCS(-1))
Output:
Number of threads : 8
Setting Number of Threads using GOMAXPROCS runtime function.
runtime.GOMAXPROCS(17)
fmt.Printf("Number of threads : %v\n", runtime.GOMAXPROCS(-1))
Output:
Number of threads : 17
Hope you like it!
Learn more about Golang Goroutine Mutex from the official Documentation.