Mutual Exclusion of Concurrent Goroutines Using WaitGroup
In your code, you have three concurrent goroutines that need to execute without interference from each other during specific sections of their code. This concept is known as mutual exclusion, and it ensures that only one goroutine can execute a critical section of code at a time.
To achieve mutual exclusion using WaitGroup, you can follow these steps:
Here's an example that implements the above steps:
<code class="go">package main import ( "fmt" "sync" ) var ( mutex1 sync.Mutex mutex2 sync.Mutex mutex3 sync.Mutex wg sync.WaitGroup ) func Routine1() { mutex1.Lock() defer mutex1.Unlock() // Do something for i := 0; i < 200; i++ { mutex2.Lock() mutex3.Lock() fmt.Println("value of z") mutex2.Unlock() mutex3.Unlock() } // Do something } func Routine2() { mutex2.Lock() defer mutex2.Unlock() // Do something for i := 0; i < 200; i++ { mutex1.Lock() mutex3.Lock() fmt.Println("value of z") mutex1.Unlock() mutex3.Unlock() } // Do something } func Routine3() { mutex3.Lock() defer mutex3.Unlock() // Do something for i := 0; i < 200; i++ { mutex1.Lock() mutex2.Lock() fmt.Println("value of z") mutex1.Unlock() mutex2.Unlock() } // Do something } func main() { wg.Add(3) go Routine1() go Routine2() go Routine3() wg.Wait() }</code>
In this example, the critical section of each goroutine is the loop where it executes fmt.Println("value of z"). The mutexes ensure that only one goroutine can execute this section at a time. The WaitGroup ensures that the main goroutine waits for all goroutines to complete before exiting.
The above is the detailed content of How can I achieve mutual exclusion in concurrent goroutines using WaitGroup?. For more information, please follow other related articles on the PHP Chinese website!