-
Notifications
You must be signed in to change notification settings - Fork 0
/
gomut.py
109 lines (84 loc) · 2.06 KB
/
gomut.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import time
from multiprocessing import Process, Queue
import queue
import unittest
def go(func, *args):
p = Process(target=func, args=args)
p.start()
def select(chans):
while True:
for c, h in chans.items():
try:
val = c._queue.get(False)
except queue.Empty:
continue
h(val)
return
class chan:
def __init__(self):
self._queue = Queue()
self._closed = False
def __iter__(self):
return self
def __next__(self):
try:
return self.get()
except queue.Empty:
raise StopIteration
def put(self, x):
self._queue.put(x)
def get(self):
if self._closed:
return self._queue.get(False)
else:
return self._queue.get()
def close(self):
self._closed = True
class TestGoLib(unittest.TestCase):
def test_go(self):
c = chan()
def f():
c.put('hi!')
go(f)
self.assertEqual(c.get(), 'hi!')
def sq(x):
c.put(x*x)
go(sq, 12)
self.assertEqual(c.get(), 144)
def test_chan(self):
c = chan()
c.put(1)
self.assertEqual(c.get(), 1)
c.put(2)
c.put(3)
self.assertEqual(c.get(), 2)
self.assertEqual(c.get(), 3)
def test_select(self):
c1 = chan()
c2 = chan()
def f1():
time.sleep(1)
c1.put('one')
go(f1)
def f2():
time.sleep(2)
c2.put('two')
go(f2)
res = []
for i in range(0, 2):
select({
c1: lambda x: res.append(x),
c2: lambda x: res.append(x),
})
self.assertEqual(res, ['one', 'two'])
def test_range(self):
c = chan()
c.put('one')
c.put('two')
c.close()
res = []
for elem in c:
res.append(elem)
self.assertEqual(res, ['one', 'two'])
if __name__ == '__main__':
unittest.main()