Help needed with goroutine synchronization in Go

Hello everyone,

I’m presently working on a Go project, and goroutine synchronization is giving me problems. I need to make sure that all of my goroutines are correctly synchronized because I have several of them running concurrently with each other.

I want to ensure that only one goroutine may access a shared resource at a time in a scenario where numerous goroutines are using it. Although I’ve heard of mutexes and channels in Go, I’m not sure which strategy would be most appropriate for my circumstances.

Could an individual give instructions or samples for properly synchronizing goroutines in Go? Any guidance or help would be much valued.

Thank you in advance!

Does this help you at all Go by Example: Mutexes ?

package main

import (
“fmt”
“sync”
“time”
)

var (
resource int // Shared resource
mutex sync.Mutex // Mutex object for synchronization
wg sync.WaitGroup // Wait group for goroutine synchronization
)

func main() {
numWorkers := 5 // Number of goroutines
wg.Add(numWorkers)

for i := 0; i < numWorkers; i++ {
	go worker(i)
}

wg.Wait() // Wait for all goroutines to finish

}

func worker(id int) {
defer wg.Done()

for i := 0; i < 5; i++ {
	// Start synchronization for the shared resource
	mutex.Lock()
	// Access the shared resource and perform the operation
	resource++
	fmt.Printf("Worker %d: Resource value: %d\n", id, resource)
	// End synchronization
	mutex.Unlock()

	time.Sleep(time.Millisecond * 100) // Delay between operations
}

}

In the given example, the resource variable represents the shared resource accessed by multiple goroutines. The mutex object is a Mutex used for synchronization to ensure exclusive access to the shared resource. The wg variable is a sync.WaitGroup used to wait for all goroutines to complete.

The worker() function is the function executed by each goroutine. It performs 5 iterations of work. Before performing the work, the mutex.Lock() function is used to lock the mutex, preventing other goroutines from accessing the resource. After performing the work, the mutex.Unlock() function is used to unlock the mutex, allowing other goroutines to access the resource.

By using the mutex to synchronize access to the shared resource, race conditions between goroutines are avoided, and data consistency is maintained.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.