Mutual Exclusion of Concurrent Goroutines with Mutex Locks
In your code, you want to ensure that specific code sections in each goroutine execute in isolation. This prevents simultaneous execution of these sections by other goroutines. Here's how mutual exclusion can be achieved using mutex locks:
The provided code outline demonstrates the flow of goroutines and the need for mutual exclusion. You want to prevent execution from passing to other goroutines while certain events are being executed in one goroutine.
To implement this, a mutex lock can be used. A mutex ensures that only one goroutine can access a shared resource at any given time. Here's a slightly modified version of your code that utilizes mutexes for mutual exclusion:
<code class="go">package main import ( "fmt" "rand" "sync" ) var ( mutex1, mutex2, mutex3 sync.Mutex wg sync.WaitGroup ) func Routine1() { mutex1.Lock() // Do something for i := 0; i < 200; i++ { mutex2.Lock() mutex3.Lock() fmt.Println("Value of z") mutex2.Unlock() mutex3.Unlock() } // Do something mutex1.Unlock() wg.Done() } func Routine2() { mutex2.Lock() // Do something for i := 0; i < 200; i++ { mutex1.Lock() mutex3.Lock() fmt.Println("Value of z") mutex1.Unlock() mutex3.Unlock() } // Do something mutex2.Unlock() wg.Done() } func Routine3() { mutex3.Lock() // Do something for i := 0; i < 200; i++ { mutex1.Lock() mutex2.Lock() fmt.Println("Value of z") mutex1.Unlock() mutex2.Unlock() } // Do something mutex3.Unlock() wg.Done() } func main() { wg.Add(3) go Routine1() go Routine2() Routine3() wg.Wait() }</code>
Here's how this updated code achieves mutual exclusion:
This implementation ensures that the specified code sections in each goroutine execute in isolation, preventing simultaneous execution from other goroutines.
The above is the detailed content of How can Mutex Locks be used to achieve Mutual Exclusion in Concurrent Goroutines?. For more information, please follow other related articles on the PHP Chinese website!