forked from shibing624/python-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcondition_demo.py
More file actions
65 lines (54 loc) · 1.47 KB
/
condition_demo.py
File metadata and controls
65 lines (54 loc) · 1.47 KB
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
# -*- coding: utf-8 -*-
"""
@author:XuMing([email protected])
@description:
"""
import threading
import time
def sleep_time(times):
time.sleep(times)
return 'ok'
class Hider(threading.Thread):
def __init__(self, cond, name):
super(Hider, self).__init__()
self.cond = cond
self.name = name
def run(self):
time.sleep(1)
# 确保先运行Seeker中的方法
self.cond.acquire()
# b
print(self.name + ': 我已经把眼睛蒙上了')
self.cond.notify()
self.cond.wait(timeout=5)
# c
# f
print(sleep_time(6))
print(self.name + ': 我找到你了 ~_~')
self.cond.notify()
self.cond.release()
# g
print(self.name + ': 我赢了')
# h
class Seeker(threading.Thread):
def __init__(self, cond, name):
super(Seeker, self).__init__()
self.cond = cond
self.name = name
def run(self):
self.cond.acquire()
self.cond.wait()
# a #释放对琐的占用,同时线程挂起在这里,直到被notify并重新占有琐。
# d
print(self.name + ': 我已经藏好了,你快来找我吧')
self.cond.notify()
self.cond.wait()
# e
# h
self.cond.release()
print(self.name + ': 被你找到了,哎~~~')
cond = threading.Condition()
seeker = Seeker(cond, 'seeker')
hider = Hider(cond, 'hider')
seeker.start()
hider.start()