This is a creation in Article, where the information may have evolved or changed.
For complex types such as container/list, you need to use Sync.mutex mutexes on all read and write operations to ensure data consistency, and in the case of mutex concurrency, the lock operation is blocked until other threads unlock. But sometimes, because there is a lengthy operation that takes up locks, we want to keep other threads from blocking on lock and go straight to other business processes.
To give a very simple scenario: in a multiplayer draw, in order to ensure that there is no negative inventory, we can through the competition lock, the first person to acquire the lock may win, while the other requests to acquire the lock failed (rather than always blocked in lock ()), directly as the winning process.
Think about, there is a thought, we can use two locks, the first lock to determine the lock state, the second lock is the real time-consuming task of the lock.
Directly on the code
type NBLocker struct{l1 sync.Mutexl2 sync.Mutexlocked bool}func (NBLocker *NBLocker) Lock() (success bool) {NBLocker.l1.Lock()defer NBLocker.l1.Unlock()if NBLocker.locked == false {NBLocker.locked = truesuccess = trueNBLocker.l2.Lock()}return}func (NBLocker *NBLocker) Unlock() {NBLocker.l1.Lock()defer NBLocker.l1.Unlock()NBLocker.locked = falseNBLocker.l2.Unlock()}
Use
type foo struct {mux NBLocker}func (self *foo) Bong(wg *sync.WaitGroup) {defer wg.Done()if !self.mux.Lock() {fmt.Println("获取锁失败")return}defer self.mux.Unlock()time.Sleep(time.Second) //停顿一秒fmt.Println("bong~")}func main() {f := &foo{}wg := &sync.WaitGroup{}wg.Add(4)go f.Bong(wg)go f.Bong(wg)go f.Bong(wg)time.Sleep(time.Second *2)go f.Bong(wg)wg.Wait()}
If the second lock fails, the Nblocker.lock () method will return false directly, and you can skip the "Lottery link" simply by judging it.
The above example output
获取锁失败获取锁失败bong~bong~