I have two concurrent go routines like below,
Routine 1{
routine procedure
critical section{
}
routine procedure
}
Routine 2{
routine procedure
critical section{
}
routine procedure
}
Is it possible by using some go inbuilt functions to implement critical section ?
Here's a channel based equivalent to Atom's solution. Do this before starting your goroutines:
and then pass this channel as a parameter when you start goroutines. Note that there is just one channel. All goroutines use this same channel.
This will let you use this channel like a mutex. Replace your pseudocode,
with
and then replace the matching closing brace of your critical section pseudocode with,
It reads nicely that way and is more descriptive than general terms like "mutex" or "critical section."
This serializes your file modification jobs and ensures that only one goroutine at a time can be be doing them. I think this is the common concept of a critical section, but if you really need other goroutines to stop, even if they are just doing the message sending jobs, well, that's a different problem.
You could try using a buffered channel:
This will buffer the data sent before actually sending it.
Do you mean something like this?
Output:
I don't think, there is any library in go to implement critical section. I think Arpssss is asking for a library.
Your question:
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):Several approaches are possible. A simple one is to use channels typed for the full "event".