上一篇简单的介绍了下多进程,对python的并发有了一定的了解, 再将多线程相对来说就相对容易,主要就是说明下threading的用法以及线程锁。
1、threading
import threading
mylock = threading.RLock()
num=0
class myThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.t_name = name
def run(self):
global num
while True:
mylock.acquire()
print 'Thread(%s) locked, Number: %d'%(self.t_name, num)
if num>=100:
mylock.release()
print 'Thread(%s) released, Number: %d'%(self.t_name, num)
break
num+=1
print 'Thread(%s) released, Number: %d'%(self.t_name, num)
mylock.release()
if __name__== '__main__':
thread1 = myThread('A')
thread2 = myThread('B')
thread1.start()
thread2.start()
threading跟multiprocessing模块类似,主要是讲下面的线程同步。插一句,有事可能会用到Timer对象处理一些定时操作
timer = threading.Timer(5.0,func)
timer.start()
2、线程同步
A、Locke和RLocke对象
两者的用法一样,RLock的用法前面的代码有介绍,这里主要是说下两者的区别:RLock允许在同一线程中被多次acquire,而Lock却不允许这种情况,如果使用RLock,那么acquire和release必须成对出现。
B、Condition
Python的Condition对象提供了对复制线程同步的支持。使用Condition对象可以在某些事件触发后才处理数据。Condition对象除了具有acquire方法和release的方法外,还有wait方法、notify方法、notifyAll方法等用于条件处理。
import threading
import time
class Producer(threading.Thread):
def run(self):
global count
while True:
if con.acquire():
if count > 1000:
con.wait()
else:
count = count+100
msg = self.name+' produce 100, count=' + str(count)
print msg
con.notify()
con.release()
time.sleep(1)
class Consumer(threading.Thread):
def run(self):
global count
while True:
if con.acquire():
if count < 100:
con.wait()
else:
count = count-3
msg = self.name+' consume 3, count='+str(count)
print msg
con.notify()
con.release()
time.sleep(1)
count = 500
con = threading.Condition()
def test():
for i in range(2):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()
if __name__ == '__main__':
test()