forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
building-h2o.py
70 lines (60 loc) · 1.76 KB
/
building-h2o.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Time: O(n)
# Space: O(1)
import threading
class H2O(object):
def __init__(self):
self.__l = threading.Lock()
self.__nH = 0
self.__nO = 0
self.__releaseHydrogen = None
self.__releaseOxygen = None
def hydrogen(self, releaseHydrogen):
with self.__l:
self.__releaseHydrogen = releaseHydrogen
self.__nH += 1
self.__output()
def oxygen(self, releaseOxygen):
with self.__l:
self.__releaseOxygen = releaseOxygen
self.__nO += 1
self.__output()
def __output(self):
while self.__nH >= 2 and \
self.__nO >= 1:
self.__nH -= 2
self.__nO -= 1
self.__releaseHydrogen()
self.__releaseHydrogen()
self.__releaseOxygen()
# Time: O(n)
# Space: O(1)
# TLE
class H2O2(object):
def __init__(self):
self.__nH = 0
self.__nO = 0
self.__cv = threading.Condition()
def hydrogen(self, releaseHydrogen):
"""
:type releaseHydrogen: method
:rtype: void
"""
with self.__cv:
while (self.__nH+1) - 2*self.__nO > 2:
self.__cv.wait()
self.__nH += 1
# releaseHydrogen() outputs "H". Do not change or remove this line.
releaseHydrogen()
self.__cv.notifyAll()
def oxygen(self, releaseOxygen):
"""
:type releaseOxygen: method
:rtype: void
"""
with self.__cv:
while 2*(self.__nO+1) - self.__nH > 2:
self.__cv.wait()
self.__nO += 1
# releaseOxygen() outputs "O". Do not change or remove this line.
releaseOxygen()
self.__cv.notifyAll()