Skip to content

Commit 29accfd

Browse files
committed
add thread task and yield demos.
1 parent 5aa6617 commit 29accfd

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

13.system/task.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
2+
import _thread
3+
4+
import time
5+
6+
class task(object):
7+
8+
lock = _thread.allocate_lock()
9+
10+
def __init__(self):
11+
self.alive = False
12+
13+
def run(self):
14+
if task.lock.acquire():
15+
while self.alive:
16+
time.sleep(0.25)
17+
print("running")
18+
task.lock.release()
19+
_thread.exit()
20+
21+
def stop(self):
22+
self.alive = False
23+
if task.lock.acquire():
24+
print("stop")
25+
task.lock.release()
26+
27+
def start(self):
28+
self.stop()
29+
self.alive = True
30+
if task.lock.acquire():
31+
print("start")
32+
_thread.start_new_thread(self.run, ())
33+
task.lock.release()
34+
35+
if __name__ == "__main__":
36+
tmp = task()
37+
tmp.start()
38+
time.sleep(1)
39+
tmp.start()
40+
time.sleep(2)
41+
tmp.start()
42+
# time.sleep(3)
43+
tmp.stop()
44+

13.system/yield.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
2+
def event():
3+
print('start yield')
4+
one = yield 'get_one' # return next(task) and yield next(task.send('set_two'))
5+
assert(one == 'set_two')
6+
print(one)
7+
yield 'get_two' # return next(task) and yield next(task.send('set_two'))
8+
print('exit yield')
9+
yield # yield next() to exit or raise StopIteration
10+
11+
task = event()
12+
run_one = next(task) # need next(task) init and next(task) == task.send(None)
13+
# so next(task) => yield 'get_one' => run_one = 'get_one'
14+
assert(run_one == 'get_one')
15+
run_two = task.send('set_two')
16+
assert(run_two == 'get_two')
17+
print('run : ', run_one, ' and ', run_two)
18+
19+
try:
20+
next(task)
21+
print('run end')
22+
next(task) # will raise StopIteration
23+
except Exception as e:
24+
print('yield StopIteration')

0 commit comments

Comments
 (0)