Home >Backend Development >Golang >Do I need to unlock it before broadcasting?

Do I need to unlock it before broadcasting?

王林
王林forward
2024-02-14 20:30:10649browse

Do I need to unlock it before broadcasting?

php editor Xiaoxin is here to reveal a popular question for everyone: "Do I need to unlock it before broadcasting?" For this question, the answer is yes. In the modern television industry, unlocking operations are usually required before programs can be broadcast. This is because unlocking ensures the safe transmission of program signals and effectively prevents unauthorized viewing. In addition, unlocking can also protect the legitimate rights and interests of copyrights and program content, and provide a high-quality viewing experience for the majority of viewers. Therefore, before watching any show, please make sure the unlocking operation is completed to avoid missing out on exciting content.

Question content

I am confused about the behavior of condition variables in Go.

In the main goroutine, I acquire the lock and call Cond.Wait() in the for loop to check the shared memory. In the working goroutine, I acquire the lock and modify the shared memory, then broadcast.

I noticed that when Cond.Wait() resumes, it tries to acquire the lock before returning. However, Cond.Broadcast() does not release the lock. So if I don't release the lock myself before broadcasting, shouldn't there be a deadlock?

I read some code using sync.Cond and found that it is not necessary, but don't know why.

Solution

Must keep the lock when modifying shared variables. When a goroutine calls Wait, the lock is unlocked so another goroutine can lock it and modify the shared variable. That goroutine may or may not hold the lock when you call Broadcast. If the goroutine holds the lock, the waiting goroutines will be awakened and wait until they can acquire the lock. When you unlock, one of the waiting goroutines can acquire the lock and continue.

So, no, as long as the broadcast goroutine eventually releases the lock, there will be no deadlock.

The above is the detailed content of Do I need to unlock it before broadcasting?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete
Previous article:How to write link in linkNext article:How to write link in link