Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The principle and usage of sync.Mutex mutex

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the principle and use of sync.Mutex mutex. The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn the principle and use of sync.Mutex mutex.

Description:

Mutexes are used to ensure that only one routine can access an object at any one time. The initial value of Mutex is unlocked. Mutex is typically used as an anonymous field for other structures, giving the structure Lock and Unlock methods. Mutex can be safely used in parallel in multiple routines.

Interpretation of sync.Mutex source code

The / / Locker interface wraps the basic Lock and UnLock methods for locking and unlocking. Type Locker interface {Lock () Unlock ()} / / Lock is used to lock m, and if m is already locked, Lock will be blocked until m is unlocked. Func (m * Mutex) Lock () / / Unlock is used to unlock m, which throws a panic if m is not locked. Func (m * Mutex) Unlock ()

Demo

Package mainimport ("fmt"sync"time") type Work struct {sync.Mutex} func main () {work: = Work {} done: = make (chan int) for I: = 0; I < 10 Work.Lock + {go func (I int) {work.Lock () defer work.Unlock () time.Sleep (1 * time.Second) done

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report