9.2 线程同步 --- python 作者:xieaotian发表于2009-06-05 16:53:59
9.2.1 简单的线程同步
# -*- coding:utf-8 -*-
# file: syn.py
#
import threading
import time
class mythread(threading.Thread): #通过继承创建类
def __init__(self, threadname): #初始化方法
threading.Thread.__init__(self, name = threadname) #调用父类的初始化方法
def run(self): #重载run
global x
lock.acquire() #调用lock的acquire方法
for i in range(3):
x = x + 1
time.sleep(2) #调用sleep函数,让线程休眠2s
print x
lock.release() #调用lock的release方法
lock = threading.RLock() #生成RLock对象
tl = []
for i in range(10):
t = mythread(str(i)) #类实例化
tl.append(t) #将类对象添加到列表中
x=0
for i in tl:
i.start() #依次运行线程
1)有LOCK的时候
>>> 3
6
9
12
15
18
21
24
27
30
>>> 30303030303030303030 #删除掉LOCK
>>> 3 #删除掉LOCK 和sleep(2)
6
9
12
15
18
21
24
27
30
9.2.2 使用条件变量保持线程同步
# -*- coding:utf-8 -*-
#file: P_C.py
#
import threading
class Producer(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self, name = threadname)
def run(self):
global x
print 'Producer'
con.acquire()
if x == 1000000:
print "Producer con.wait()"
con.wait()
pass
else:
for i in range(1000000):
x = x + 1
print "Producer con.notify()"
con.notify()
print x
con.release()
class Consumer(threading.Thread):
def __init__(self, threadname):
threading.Thread.__init__(self, name = threadname)
def run(self):
global x
print 'Consumer'
con.acquire()
if x == 0:
print "Consumer con.wait()"
con.wait()
pass
else:
for i in range(1000000):
x = x - 1
print "Consumer con.notify()"
con.notify()
print x
con.release()
con = threading.Condition()
x = 0
p = Producer('Producer')
c = Consumer('Consumer')
#c.start()
p.start()
c.start()
#c.join()
p.join()
c.join()
print x
1)先c.start()
c.start()
p.start()
c.join()
p.join()
2)先p.start()
p.start()
c.start()
p.join()
c.join()
>>> Consumer
Consumer con.wait()
Producer
Producer con.notify()
1000000
1000000
1000000
>>> Producer
Consumer
Producer con.notify()
1000000
Consumer con.notify()
0
0
