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

Detailed explanation of the use of sync.Cond in Go language

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the "detailed explanation of the use of sync.Cond in the Go language". In the daily operation, I believe that many people have doubts about the detailed explanation of the use of sync.Cond in the GE language. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "detailed explanation of the use of sync.Cond in the Go language"! Next, please follow the editor to study!

Catalogue

What can sync.Cond be used for?

The difference from Sync.Mutex

Sync.Cond usage scenario

Sync.Cond

What are the methods of sync.Cond

NewCond creates an instance

Broadcast broadcast awakens all

Signal awakens a co-worker

Wait wait

Code example

What can sync.Cond be used for?

Cond in Golang's sync package implements a conditional variable that can use multiple Reader to wait for a common resource.

Each Cond is associated with a Lock. When the condition is modified or the Wait method is called, it must be locked to protect the Condition. It is somewhat similar to Wait and NotifyAll in Java.

The sync.Cond condition variable is used to coordinate those goroutine that want to share the resource, and can be used to notify the gorountine blocked by the mutex when the state of the shared resource changes.

The difference from Sync.Mutex

Sync.Cond is based on mutexes. What's the difference between mutexes and mutexes?

Sync.Mutex is usually used to protect critical areas and shared resources, and the condition variable sync.Cond is used to coordinate shared resources that you want to access.

Sync.Cond usage scenario

One of the co-programs is receiving data, and other co-programs must wait for the data to be received before the correct data can be read.

In the above case, if you simply use channel or mutex, only one co-program can wait and read the data, and there is no way to inform other co-programs to also read the data.

What should I do at this time?

A global variable can be used to identify whether the first protocol has finished receiving data, and the rest of the program repeatedly checks the value of the variable until the data is read.

It is also possible to create multiple channel, each of which is blocked on a Channel, and is notified by the receiving data one by one after the data is received.

Then a sync.Cond is actually built into Go to solve this problem.

Sync.Cond

/ Each Cond has an associated Locker L (often a * Mutex or * RWMutex), / / which must be held when changing the condition and// when calling the Wait method.//// A Cond must not be copied after first use.type Cond struct {noCopy noCopy / / Lis held while observing or changing the condition L Locker notify notifyList checker copyChecker}

You can see that each Cond is associated with a lock L (mutex Mutex, or read-write lock * RMMutex), which must be locked when modifying conditions or using Wait.

What are the methods of sync.Cond

NewCond creates an instance

Func NewCond (l Locker) * Cond

NewCond needs to associate a lock to create an instance.

Specific examples:

Cadence: = sync.NewCond (& sync.Mutex {}) Broadcast broadcast wakes up all

/ / Broadcast wakes all goroutines waiting on c. Universe / It is allowed but not required for the caller to hold c.L// during the call.func (c * Cond) Broadcast ()

Broadcast wakes up all goroutine waiting for condition variable c without lock protection.

Specific examples:

Go func () {for range time.Tick (1 * time.Millisecond) {cadence.Broadcast ()} () Signal wakes up a co-program

/ / Signal wakes one goroutine waiting on c, if there is any.//// It is allowed but not required for the caller to hold c.L// during the call.func (c * Cond) Signal ()

Signal only wakes up the goroutine of any one waiting condition variable c without lock protection. Somewhat similar to Notify in Java

Wait wait

/ / Wait atomically unlocks c.L and suspends execution// of the calling goroutine. After later resuming execution,// Wait locks c.L before returning. Unlike in other systems,// Wait cannot return unless awoken by Broadcast or Signal.//// Because c.L is not locked when Wait first resumes, the caller// typically cannot assume that the condition is true when// Wait returns. Instead, the caller should Wait in a loop://// c.L.Lock () / / for! condition () {/ / c.Wait () /} / /. Make use of condition. / / c.L.Unlock () / / func (c * Cond) Wait ()

Calling Wait automatically releases the lock c.L and suspends the caller's goroutine, so the current protocol blocks where the Wait method is called. If another protocol calls Signal or Broadcast to wake up the protocol, the Wait method ends blocking, relocks c.L, and continues to execute the code that follows the Wait

Code example:

C.L.Lock () for! condition () {c.Wait ()}... Make use of condition... c.L.Unlock () code example

Package syncimport ("log"sync"testing"time") var done = falsefunc read (name string, c * sync.Cond) {c.L.Lock () for! done {c.Wait ()} log.Println (name, "starts reading") c.L.Unlock ()} func write (name string, c * sync.Cond) {log.Println (name) Starts writing) time.Sleep (time.Second) c.L.Lock () done = true c.L.Unlock () log.Println (name, "wakes all") c.Broadcast ()} func TestSyncCond (t * testing.T) {cond: = sync.NewCond (& sync.Mutex {}) go read ("reader1", cond) go read ("reader2", cond) go read ("reader3", cond) write ("writer", cond) time.Sleep (time.Second * 3)}

Running result

= RUN TestSyncCond

2021-08-26 11:06:48 writer starts writing

2021-08-26 11:06:49 writer wakes all

2021-08-26 11:06:49 reader3 starts reading

2021-08-26 11:06:49 reader2 starts reading

2021-08-26 11:06:49 reader1 starts reading

-PASS: TestSyncCond (4.01s)

PASS

At this point, the study of "detailed explanation of the use of sync.Cond in Go language" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Development

Wechat

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

12
Report