-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path1116.py
81 lines (65 loc) · 2.37 KB
/
1116.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
71
72
73
74
75
76
77
78
79
80
81
__________________________________________________________________________________________________
sample 44 ms submission
from threading import Lock
class ZeroEvenOdd:
def __init__(self, n):
self.n = n
self.l_zero = Lock()
self.l_even = Lock()
self.l_odd = Lock()
self.l_even.acquire()
self.l_odd.acquire()
# printNumber(x) outputs "x", where x is an integer.
def zero(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(self.n):
self.l_zero.acquire()
printNumber(0)
try:
if i & 1:
self.l_even.release()
else:
self.l_odd.release()
except:
pass
def even(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(2, self.n+1, 2):
self.l_even.acquire()
printNumber(i)
try:
self.l_zero.release()
except:
pass
def odd(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(1, self.n+1, 2):
self.l_odd.acquire()
printNumber(i)
try:
self.l_zero.release()
except:
pass
__________________________________________________________________________________________________
sample 48 ms submission
from threading import Lock
class ZeroEvenOdd:
def __init__(self, n):
self.n = n
self.locks = (Lock(), Lock(), Lock())
self.locks[1].acquire()
self.locks[2].acquire()
# printNumber(x) outputs "x", where x is an integer.
def zero(self, printNumber) -> None:
for i in range(self.n):
self.locks[0].acquire()
printNumber(0)
self.locks[i%2+1].release()
def even(self, printNumber) -> None:
for i in range(2, self.n+1, 2):
self.locks[2].acquire()
printNumber(i)
self.locks[0].release()
def odd(self, printNumber) -> None:
for i in range(1, self.n+1, 2):
self.locks[1].acquire()
printNumber(i)
self.locks[0].release()
__________________________________________________________________________________________________