Simple implementation of Golang non-blocking lock

Source: Internet
Author: User
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()}


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


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.