Created
April 25, 2020 07:28
-
-
Save swr1bm86/89ac6fde151a2ae92149cddf79aa1b9f to your computer and use it in GitHub Desktop.
Python WaitGroup (like Go sync.WaitGroup)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading # :( | |
class WaitGroup(object): | |
"""WaitGroup is like Go sync.WaitGroup. | |
Without all the useful corner cases. | |
""" | |
def __init__(self): | |
self.count = 0 | |
self.cv = threading.Condition() | |
def add(self, n): | |
self.cv.acquire() | |
self.count += n | |
self.cv.release() | |
def done(self): | |
self.cv.acquire() | |
self.count -= 1 | |
if self.count == 0: | |
self.cv.notify_all() | |
self.cv.release() | |
def wait(self): | |
self.cv.acquire() | |
while self.count > 0: | |
self.cv.wait() | |
self.cv.release() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
调用wait()会释放Lock,直至该线程被Notify()、NotifyAll()或者超时线程又重新获得Lock.