__author__ = 'alex'
import threading
import time
x = 10
def fun(l):
global x
l.acquire()
x -= 1
time.sleep(2)
print (x)
l.release()
lock = threading.RLock()
for i in range(10):
tt = threading.Thread(target=fun,args=(lock,))
tt.start()
执行结果:
9
8
7
6
5
4
3
2
1
0
通过threading.Event()加锁,Event()会将锁之前的操作完全的锁住,Event.set()之后,就完全释放通过:
__author__ = 'alex'
import threading
def func(i,e):
print (i)
e.wait()
print (i+100)
event = threading.Event()
for i in range(10):
t = threading.Thread(target=func,args=(i,event,))
t.start()
event.clear()
inp = input(">>>>")
if inp == '1':
event.set()
执行结果:
0
1
2
3
4
5
6
7
8
9
>>>>1
102
103
106
107
100
101
104
105
108
109
Condition锁:
__author__ = 'alex'
import threading
def run(i,conn):
print (i)
conn.acquire()
conn.wait()
print (i+100)
conn.release()
c = threading.Condition()
for i in range(10):
t = threading.Thread(target=run,args=(i,c,))
t.start()
while True:
inp = input(">>>>>")
if inp == 'q':
break
else:
c.acquire()
c.notify(int(inp))
c.release()
执行结果:
0
1
2
3
4
5
6
7
8
9
>>>>>1
>>>>>100
2
>>>>>101
102
3
>>>>>105
103
104
4
>>>>>107
108
106
109
5
>>>>>5
>>>>>5
>>>>>5
用wait_for实现满足条件的时候执行一个线程
import threading
def condition():
ret = False
r = input(">>>>")
if r == 'true':
ret = True
else:
ret = False
return ret
def run(i,conn):
print (i)
conn.acquire()
conn.wait_for(condition)
print (i+100)
conn.release()
c = threading.Condition()
for i in range(10):
t = threading.Thread(target=run,args=(i,c,))
t.start()
执行结果:
0
>>>>1
2
3
4
5
6
7
8
9
t
>>>>t
>>>>t
>>>>t
>>>>t
>>>>False
>>>>true
106
>>>>true
107