
使用sync.Mutex来锁定变量可以避免竞争条件。sync.Mutex是Go语言内置的锁类型,可以在多个goroutine之间安全地共享变量。
使用RWMutex可以在读操作时加锁,写操作时再加写锁,这样可以提高性能。RWMutex是Go语言内置的读写锁类型。
Curious to learn more? Check out: Watermill Golang Sync
Mutex Basics
Mutex is a synchronization mechanism in Go that allows only one goroutine to access a shared resource at a time. It's a simple yet powerful tool that helps prevent data corruption and ensures thread safety.
A Mutex in Go is represented by a struct with two fields: state and sema. The state field indicates the current state of the mutex, while the sema field is a semaphore used to control the lock state.
To acquire a mutex, a goroutine calls the Lock method. If the mutex is not locked, the goroutine gets the lock and sets the state to 1. If the mutex is already locked, the goroutine waits until the mutex is unlocked.
Here are the four possible states of a Mutex:
When a goroutine releases a mutex, it sets the state to 0, allowing another goroutine to acquire the lock. If there are waiting goroutines, one of them will be awakened and allowed to acquire the lock.
The Mutex type in Go has two methods: Lock and Unlock. The Lock method acquires the mutex, while the Unlock method releases it. It's essential to use Mutex correctly to avoid data corruption and ensure thread safety.
Consider reading: Golang Release
Mutex Usage
Mutex is a synchronization primitive that ensures only one goroutine can access a shared resource at a time. It works by maintaining a flag, indicating whether a goroutine holds the mutex.
When a goroutine calls Lock, it checks the flag. If it's 0, the goroutine gets the mutex and sets the flag to 1; if it's 1, the goroutine waits until the flag becomes 0. When a goroutine calls Unlock, it sets the flag to 0, and if there are waiting goroutines, one of them gets the mutex and sets the flag to 1.
To use a mutex effectively, you need to pass a pointer to it when calling a function, as shown in the example: `func incr(wg *sync.WaitGroup, lock *sync.Mutex)`. If you pass a value, it won't work as expected.
Recommended read: Golang Sync
解锁过程
如果解锁时有一个或多个协程阻塞,解锁过程分为两个步骤:先把Locked置为0,然后查看Waiter>0,释放一个信号量,唤醒一个阻塞的协程。
被唤醒的协程会把Locked置为1,从而获得了锁。这个过程是如何实现的呢?在Go语言中,我们通常使用defer语句来确保Mutex能够在函数退出时被正确释放。
Use
When working with mutexes, it's essential to understand how to use them effectively.
Mutexes can be used to ensure the atomicity of operations, but they can be limited in their functionality.
To use a mutex, you need to acquire the lock before performing the operation and release it afterwards.
This is done using the `Lock()` and `Unlock()` methods of the mutex.
If a mutex is passed as a parameter to a function, it must be passed by pointer, not by value.
This is because the mutex lock is only acquired on the pointer, not on the value.
Here's an example of how to pass a mutex by pointer: `func incr(wg *sync.WaitGroup, lock *sync.Mutex)`.
If a struct contains a mutex field, and you want to use the mutex in a method of the struct, you must declare the method as a pointer method.
This is because the mutex lock is only acquired on the pointer to the struct, not on the struct itself.
Here's an example of how to declare a pointer method: `func (m *mylock) test()`.
Note that if you declare a method without a pointer receiver, like `func (m mylock) test()`, the mutex lock will not be acquired.
Intriguing read: Golang Copy Struct
This can lead to unexpected behavior, including data corruption and deadlocks.
Here's an example of how to use a mutex to protect a shared variable: `data=data+1`.
In this example, the mutex is used to ensure that only one goroutine can modify the shared variable at a time.
By using a mutex, you can ensure that your code is thread-safe and free from data corruption and deadlocks.
Mutex Patterns
Mutex Patterns are crucial in ensuring that our code runs smoothly in a concurrent environment.
In Go, Mutex has two patterns: Normal and Starving. Normal is the default pattern and allows a goroutine to spin if it can't acquire the lock immediately.
A goroutine will spin if it's not blocked by the lock, which means it will continuously check the lock's status. This can be beneficial as it allows the goroutine to potentially acquire the lock quickly, without being blocked.
However, if a goroutine spins for too long, it may lead to a "starvation" state, where other goroutines are unable to acquire the lock.
In the Starving pattern, if a goroutine spins and acquires the lock, it will release a signal to wake up a waiting goroutine. This ensures that the waiting goroutine will have a chance to acquire the lock.
However, if the waiting goroutine has been blocked for more than 1 millisecond, the Mutex will be marked as "starving" and will not allow spinning. This prevents the starvation state from occurring.
Concurrency Safety
Concurrency Safety is a crucial aspect of Go programming. Mutex (short for Mutual Exclusion) is a fundamental construct that ensures concurrent access to shared resources.
A Mutex works by maintaining a flag indicating whether a goroutine holds the lock. When a goroutine calls Lock, it checks the flag. If it's 0, the goroutine gets the lock and sets the flag to 1; if it's 1, the goroutine waits until the flag is 0.
To avoid deadlocks, it's essential to ensure that every lock acquisition has a corresponding unlock operation, and never acquire the same lock twice while holding it.
To avoid I/O operations while holding a lock, it's best to release the lock before performing I/O operations.
Here's a summary of the synchronization mechanisms:
RWMutex
RWMutex is a type of mutex in Go that allows for fine-grained control over concurrency. It's a read-write mutex, which means it doesn't restrict concurrent reads, but it does prevent concurrent reads and writes, or concurrent writes.
A RWMutex is implemented as a struct with five fields: w, writerSem, readerSem, readerCount, and readerWait. The w field is a mutex that's reused to provide locking capabilities. The writerSem and readerSem fields are semaphores that manage the waiting of writers and readers, respectively. The readerCount field keeps track of the number of readers currently executing, and the readerWait field stores the number of readers waiting for a write operation to complete.
Here's a summary of the behavior of a RWMutex:
This means that multiple readers can access the same resource simultaneously, but a writer will block all readers until it's done. A writer will also block other writers until it's done.
In practice, a RWMutex is useful when you have a resource that's mostly read-only, but occasionally needs to be updated. By using a RWMutex, you can ensure that updates are atomic and won't interfere with concurrent reads.
Synchronization
Synchronization is a crucial concept in concurrent programming, and it's essential to understand how it works to prevent data inconsistency.
A race condition occurs when multiple threads access and modify shared data simultaneously, leading to unexpected results. This can happen when multiple threads write to the same buffer without any coordination.
Imagine two threads, A and B, accessing the same account balance. If thread A is updating the balance to 3000 and thread B is deducting 2000 at the same time, they might both read the initial balance of 500, resulting in an inconsistent outcome.
To avoid this, we need to synchronize the access to shared resources. Synchronization is the process of coordinating multiple threads to access shared resources in a mutually exclusive manner.
Think of synchronization as a lock that prevents multiple threads from accessing the same resource simultaneously. When a thread wants to access a shared resource, it must acquire the lock first, and when it's done, it releases the lock, allowing other threads to access the resource.
A critical section is a code segment that requires exclusive access to a shared resource. In the example of updating the account balance, the code that updates the balance is a critical section that needs to be protected by synchronization.
By synchronizing access to shared resources, we can ensure that multiple threads access the resources in a serialized manner, preventing data inconsistency and ensuring that the program behaves as expected.
A unique perspective: Golang Source Code
Concurrency Control
Concurrency Control is a fundamental aspect of Go programming, ensuring that shared resources are accessed safely and efficiently. This is where Mutex comes in, a synchronization mechanism that guarantees exclusive access to shared variables.
Mutex works by maintaining a flag indicating whether a goroutine holds it. When a goroutine calls Lock, it checks the flag. If it's 0, the goroutine gets the Mutex and sets the flag to 1; if it's 1, the goroutine waits until the flag is 0.
Unlocking a Mutex is straightforward: the goroutine sets the flag to 0, releasing the Mutex. If other goroutines are waiting, one of them can acquire the Mutex and set the flag to 1. This mutual exclusion ensures that only one goroutine can access the shared resource at a time.
Go Language

In Go Language, synchronization is crucial when dealing with shared variables.
The readerCount variable is initially set to 0.
When a reader arrives, readerCount is incremented to 1.
A writer that arrives first will save the value of readerCount in readerWait and set readerCount to a large negative value, -10000.
This is a crucial step in detecting subsequent readers and writers.
If another writer arrives while the first writer holds the lock, it will block.
Subsequent readers will also block if they find a negative readerCount value.
The readerCount variable is decremented by 1 when a reader finishes its operation, and if the value is negative, it knows a writer is waiting and enters a slow unlock mode, decrementing readerWait by 1.
Go 语言中的原子操作
原子操作是一种更新变量的操作,保证了操作的原子性,不会被其他线程中断。
Go 提供了 sync/atomic 包来实现原子操作,提供了各种原子操作函数,例如 LoadInt32 和 StoreInt32。
这些函数可以让我们安全地更新变量的值,而不用担心其他线程会干扰我们。
Go 的原子操作可以让我们写出更高效和更安全的多线程程序。
Broaden your view: Golang Go
Example
In Go, a language designed for concurrent programming, synchronization is crucial to prevent data corruption and ensure thread safety. A common synchronization technique is using mutexes to protect shared resources.

When a reader acquires a mutex, the readerCount variable is incremented by one, making it 1. This indicates the presence of a reader.
A writer, however, must first acquire the mutex and then save the current readerCount value in the readerWait variable before setting the readerCount to a large negative value, typically -10000. This is a key step in writer synchronization.
If another writer attempts to acquire the mutex while a writer is holding it, the second writer will block. This is because the first writer has already acquired the mutex.
When a reader acquires the mutex and finds the readerCount to be negative, it knows that there is a writer waiting and will block itself. This is a critical aspect of reader synchronization.
Upon completion of its operation, a reader will decrement the readerCount, but if it finds the value to be negative, it will know that there are waiting writers and enter a slow unlock mode, decrementing the readerWait variable. If the readerWait reaches zero, it will wake up the waiting writer.

Here's a step-by-step breakdown of the synchronization process:
- Reader acquires mutex and increments readerCount to 1.
- Writer acquires mutex, saves readerCount in readerWait, and sets readerCount to a large negative value (-10000).
- Writer blocks any subsequent writers.
- Reader acquires mutex, finds readerCount negative, and blocks itself.
- Reader completes operation, decrements readerCount (still negative), and enters slow unlock mode.
- Reader decrements readerWait, wakes up waiting writer if it reaches zero.
Example and Usage
When using locks in Go, it's essential to understand how to use them effectively.
To lock a mutex, you need to call the Lock method on it. You can also use a defer statement to ensure that the lock is released even if an error occurs.
If you pass a mutex as a value to a function, it won't work as expected. You need to pass it as a pointer, like this: func incr(wg *sync.WaitGroup, lock *sync.Mutex).
In Go, locks are often used in conjunction with WaitGroups to synchronize concurrent operations.
A common pattern is to use a mutex to protect a shared variable, and a WaitGroup to wait for all goroutines to finish.
Here's an example of how to use a mutex to protect a shared variable:
In the example above, the mutex is used to protect the shared variable "data". The Lock method is called before accessing the variable, and the Unlock method is called after accessing it.

When using a mutex to protect a shared variable, it's essential to understand the concept of slow unlock.
In the example above, when the reader finishes its operation, it checks the value of the shared variable. If it's negative, it means there's a waiting writer, and the reader will enter slow unlock mode.
Featured Images: pexels.com


