1.线程同步
<1>简单的线程同步使用
使用Thread对象的Lock和RLock可以事先简单的线程同步,RLock和Lock偶具有acquire方法和release方法
'''
Created on 2015-1-7
@author: huangpeng03
'''
import threading
import time
x =0
class mythread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name=threadname)
def run(self):
global x
lock.acquire()
for i in range(3):
x = x+1
time.sleep(2)
print x
lock.release()
if __name__ == '__main__':
lock = threading.RLock()
t1 = []
for i in range(10):
t = mythread(str(i))
t1.append(t)
for i in t1:
i.start()
结果:每隔2s打印一次
3
6
9
12
15
18
21
24
27
30
<2>使用条件变量保持线程同步
python的Condition对象提供了对复杂线程同步的支持,使用Condition对象可以在某县时间出发后才处理数据
Condition对象除了具有acquire方法和release方法以外,还有wait、notify、notifyAll等方法用于条件处理
'''
Created on 2015-1-8
@author: huangpeng03
'''
import threading
class Producer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
global x
con.acquire()
if x == 1000000:
con.wait()
pass
else:
for i in range(1000000):
x = x+1
con.notify()
print x
con.release()
class Consumer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self)
def run(self):
global x
con.acquire()
if x == 0:
con.wait()
pass
else:
for i in range(1000000):
x = x-1
con.notify()
print x
con.release()
x = 0
if __name__ == '__main__':
con = threading.Condition()
p = Producer('Producer')
c = Consumer('Consumer')
p.start()
c.start()
p.join()
c.join()
print x
结果;
1000000
0
0