Mutex: How to expand additional functions?

We have learned the basic usage, implementation principles and error-prone scenarios of Mutex, which can be said to cover all aspects of Mutex. If you can master these contents, then, in most development scenarios, you can be handy.

However, in some specific scenarios, these basic functions are not enough. At this time, we need to develop some extension functions. Let me give a few examples.

For example, we know that if a mutex is acquired by a goroutine and has not been released, then other goroutines that request the lock will block and wait until they have a chance to acquire the lock. Sometimes blocking is not a very good idea. For example, if you request a lock to update a counter, if you can’t get the lock, there is no need to wait. At worst, if you don’t update this time, I will update it next time. If you block, it will lead to business processing decline in capacity.

For another example, if we want to monitor the lock competition, a monitoring indicator is the number of goroutines waiting for the lock. We can push this indicator to the time series database, and then display it through some monitoring systems (such as Grafana). You must know that locks are one of the "culprits" of performance degradation, so effectively reducing lock competition can greatly improve performance. Therefore, monitoring the number of goroutines waiting on key mutexes is an important indicator for us to analyze the intensity of lock competition.

In fact, no matter whether the goroutine that does not want the lock continues to wait, or wants to monitor the lock, we can add some additional functions to the Mutex through Hacker based on the implementation of the Mutex in the standard library. In this lesson, I will teach you to implement several extended functions, including implementing TryLock, obtaining indicators such as the number of waiters, and implementing a thread-safe queue.

TryLock

Guess you like

Origin blog.csdn.net/guofeidageda/article/details/130064953