Created
August 18, 2021 07:25
-
-
Save QGB/7ff7b21efec89b338a460ab208a716d5 to your computer and use it in GitHub Desktop.
leetcode print-zero-even-odd
This file contains 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 | |
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