Skip to content

Instantly share code, notes, and snippets.

@QGB
Created August 18, 2021 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save QGB/7ff7b21efec89b338a460ab208a716d5 to your computer and use it in GitHub Desktop.
Save QGB/7ff7b21efec89b338a460ab208a716d5 to your computer and use it in GitHub Desktop.
leetcode print-zero-even-odd
import threading
cz= threading.Condition()
cq= threading.Condition()
ce= threading.Condition()
class ZeroEvenOdd:
def __init__(self, n):
self.n = n
self.q=1
self.e=2
# printNumber(x) outputs "x", where x is an integer.
def zero(self, printNumber: 'Callable[[int], None]') -> None:
with cz:
while self.e < self.n and self.q < self.n:
printNumber(0)
if self.q<self.e:
ce.notifyAll()
else:
cq.notifyAll()
cz.wait()
ce.notifyAll()
cq.notifyAll()
def even(self, printNumber: 'Callable[[int], None]') -> None:
with ce:
while self.e < self.n:
ce.wait()
printNumber(self.e)
self.e+=2
cz.notifyAll()
cz.notifyAll()
def odd(self, printNumber: 'Callable[[int], None]') -> None:
with cq:
while self.q < self.n:
cq.wait()
printNumber(self.q)
self.q+=2
cz.notifyAll()
cz.notifyAll()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment