- Go provides very good support for concurrency using Go Routines or channels.
- It takes advantage of efficient memory management strategies and multicore processor architecture for implementing concurrency.
Construct | Package | Description | Sample Code |
---|---|---|---|
Mutex | sync | We can use a mutex to safely access data across multiple goroutines. - Lock the mutex before accessing counters; unlock it at the end of the function using a defer statement.- sync.RWMutex lets multiple goroutines read simultaneously (via RLock ), but still enforces exclusive access for writes (Lock). |
type Test struct { mu sync.Mutex } - c.mu.Lock() - defer c.mu.Unlock() - c.counter++ |
WaitGroup | sync | A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add() to set the number of goroutines to wait for. | var wg sync.WaitGroup - wg.Add(1) // Always call wg.Add() before you launch the goroutine that will call wg.Done().- wg.Done() //Recommended to call WaitGroup.Done() deferred, so it gets called even if the goroutine panics.- wg.Wait() //wg.Wait() will block until wg.Done() is called. |
Once | sync | Once is an object that will perform exactly one action. | var once sync.Once - once.Do(func() {singleInstance = new(single)} ) |