Skip to content

Instantly share code, notes, and snippets.

@zjhmale
Created April 25, 2020 07:28
Show Gist options
  • Save zjhmale/89ac6fde151a2ae92149cddf79aa1b9f to your computer and use it in GitHub Desktop.
Save zjhmale/89ac6fde151a2ae92149cddf79aa1b9f to your computer and use it in GitHub Desktop.
Python WaitGroup (like Go sync.WaitGroup)
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()
@zjhmale
Copy link
Author

zjhmale commented Apr 25, 2020

调用wait()会释放Lock,直至该线程被Notify()、NotifyAll()或者超时线程又重新获得Lock.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment