http://www.17jo.com/program/python/app/ThreadUse.html
1. Python多线程基础
Python多线程编程,当程序需要同时并发处理多个任务时,就需要要使用多线程编程。
继承线程类threading.thread,再重载成员函数run,程序处理的代码写在函数run中,最后再调用start()方法来运行线程,而join()方法可以用来等待线程结束。
多线程的资源同步,可使用thread.RLock()来创建资源锁,然后使用acquire()来锁住资源,release()来释放资源。等待事件用thread.Event(),用wait()来等待事件,set()来激发事件,clear()用于清除已激发事件。
另外可以用isAlive()来判断线程是否存活着。
# 例:多线程编程
- #!/usr/bin/env python
- #threads1.py
- 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' # 结束程序
- >> program start # 输出
- >> Thread1 run
- >> 1
- >> 2
- >> 3
- >> Thread1 end
- >> Thread2 run
- >> Thread2 end
- >> program end
2. Python多线程编程的两种方式
http://guanjh.iteye.com/blog/88904
Python中如果要使用线程的话,python的lib中提供了两种方式。一种是函数式,一种是用类来包装的线程对象。举两个简单的例子希望起到抛砖引玉的作用,关于多线程编程的其他知识例如互斥、信号量、临界区等请参考python的文档及相关资料。
1.调用thread模块中的start_new_thread()函数来产生新的线程
请看代码:
- #!/usr/bin/env python
- #thread_example1.py
- import time
- import _thread
- def timer(no,interval):
- print('timer Begin:')
- while True:
- print('Thread :(%d) Time:%s'%(no,time.ctime()))
- time.sleep(interval)
- def test():
- print('Test Begin:')
- _thread.start_new_thread(timer,(1,1))
- _thread.start_new_thread(timer,(2,3))
- print(__name__)
- if __name__=='__main__':
- test()
- time.sleep(20) # 注意这里, 必须这样子, 因为如果不睡眠
- # test()之后程序就直接退出了, 线程都没有来得及运行
这个是thread.start_new_thread(function,args[,kwargs])函数原型,其中function参数是你将要调用的线程函数;args是讲传递给你的线程函数的参数,他必须是个tuple类型;而kwargs是可选的参数。
线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用thread.exit(),他抛出SystemExit exception,达到退出线程的目的。
2. 通过调用threading模块继承threading.Thread类来包装一个线程对象。
请看代码:
- #!/usr/bin/env python
- #thread_example2.py
- import threading
- import time
- class timer(threading.Thread): #我的timer类继承自threading.Thread类
- def __init__(self,no,interval):
- #在我重写__init__方法的时候要记得调用基类的__init__方法
- threading.Thread.__init__(self)
- self.no=no
- self.interval=interval
- def run(self): #重写run()方法,把自己的线程函数的代码放到这里
- i = 4
- while i > 0:
- print(i)
- print('Thread Object (%d), Time:%s'%(self.no,time.ctime()))
- time.sleep(self.interval)
- i = i - 1
- def test():
- threadone=timer(1,1) #产生2个线程对象
- threadtwo=timer(2,3)
- threadone.start() #通过调用线程对象的.start()方法来激活线程
- threadtwo.start()
- if __name__=='__main__':
- test()
其实thread和threading的模块中还包含了其他的很多关于多线程编程的东西,例如锁、定时器、获得激活线程列表等等,请大家仔细参考python的文档!
3. 我自己的习惯
我在使用C++时的多线程, 我更喜欢用线程函数的结束来代表线程的结束, 这样对于某些资源的释放情况更容易掌握一些