Your question:
I have N concurrent go routines (all more or less same purpose). Each of those have a critical section. Before entering critical section, each routine just do some message sending job. When it enters critical section, I need all other routines must stop execution until it exits critical section. Is it possible by using any library function in GO?
What you are asking about (to force a stop on all other goroutines while one goroutine is in the critical section) is not typical in Go programs. There is no library function to stop all other goroutines, so you will need to stop them by designing proper synchronization among goroutines in your program. The typical scenario is for all goroutines to (potentially) run concurrently, except for those goroutines that are blocked somehow.
To control concurrent access to a shared resource in a Go program you can use Go channels, the "sync"
package, pipes, or network connections.
Using sync.Mutex
, the Go code may look like this (but please keep in mind that, whenever possible, Go programs should preferably use Go channels instead of mutexes):
package main
import "sync"
var m sync.Mutex
var wg sync.WaitGroup
func routine1() {
... do something ...
m.Lock()
... critical section (access the shared resource here) ...
m.Unlock()
... do something ...
wg.Done()
}
func routine2() {
... do something ...
m.Lock()
... critical section (access the shared resource here) ...
m.Unlock()
... do something ...
wg.Done()
}
func main() {
wg.Add(1); go routine1()
wg.Add(1); go routine2()
wg.Wait()
}