您的位置:首页 > 编程语言 > Python开发

Python 多线程编程及同步处理

2012-12-09 14:18 525 查看
http://blog.chinaunix.net/space.php?uid=25808509&do=blog&id=1991798

Python多线程编程,当程序需要同时并发处理多个任务时,就需要要使用多线程编程。继承线程类threading.thread,再重载成员函数run,程序处理的代码写在函数run中,最后再调用start()方法来运行线程,而join()方法可以用来等待线程结束。

多线程的资源同步,可使用thread.RLock()来创建资源锁,然后使用acquire()来锁住资源,release()来释放资源。等待事件用thread.Event(),用wait()来等待事件,set()来激发事件,clear()用于清除已激发事件。

另外可以用isAlive()来判断线程是否存活着。

# 例:多线程编程
import time # 导入时间模块
import threading as thread # 导入线程模块
class Thread1(thread.Thread):
def __init__(self):
thread.Thread.__init__(self) # 默认初始化
self.lock = thread.RLock() # 创建资源锁
self.flag = True
self.count = 0
def run(self):
print 'Thread1 run'
while self.count < 3:
self.lock.acquire() # 锁住资源
self.count += 1
print self.count # 输出计数
self.lock.release() # 释放资源
time.sleep(1) # 线程休眠1秒
print 'Thread1 end'
class Thread2(thread.Thread):
def __init__(self,event):
thread.Thread.__init__(self) # 初始化线程
self.event = event
def run(self):
self.event.wait() # 线程启动后等待事件
print 'Thread2 run'
self.event.clear() # 清除事件
print 'Thread2 end'
print 'program start'
event = thread.Event()
t1 = Thread1()
t2 = Thread2(event)
t1.start() # 线程t1启动
t2.start() # 线程t2启动
t1.join() # 等待线程t1结束
event.set() # 激发事件t2开始运行
t2.join() # 等待线程t2结束
print 'program end' # 结束程序
>> programstart # 输出
>> Thread1 run
>> 1
>> 2
>> 3
>> Thread1 end
>> Thread2 run
>> Thread2 end
>> program end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: