Python之多线程编程学习笔记
在一个程序中,这些独立运行的程序片断叫作“线程”(Thread),利用它编程的概念就叫作“多线程处理”。多线程处理一个常见的例子就是用户界面。利用线程,用户可按下一个按钮,然后程序会立即作出响应,而不是让用户等待程序完成了当前任务以后才开始响应。
这里整理一下Python程序设计中使用多线程的几种方法。
1. 使用Thread模块相关的函数实现多线程
先写两个函数,work_one ,work_two,我希望把这两个函数同时执行。
使用Thread模块的代码如下:
import thread
from time import sleep
def work_one():
print 'John starts to work!\n'
sleep(4) #模拟工作过程
print 'John done his work!\n'
def work_two():
print 'Billy starts to work!\n'
sleep(6) #模拟工作过程
print 'Billy done his work!\n'
def main():
print '***** main *****\n'
thread.start_new_thread(work_one,())
thread.start_new_thread(work_two,())
sleep(8)
print '***** all work done! *****\n'
if __name__ == '__main__':
main()
效果图如下:
main中的sleep(8)是为了防止主线程提前终止,从而杀死运行着的两个线程。这就好比是限时赛跑,不管有没有人到达终点,限时一到,比赛结束。
如果希望主线程等所有线程执行完毕后,才终止,如常规的赛跑比赛。我们可以加上为每个线程,加上一把线程锁。
import thread
from time import sleep
def work_one(lock):
print 'John starts to work!\n'
sleep(4) #模拟工作过程
print 'John done his work!\n'
print 'lock1 release!'
lock.release()
def work_two(lock):
print 'Billy starts to work!\n'
sleep(6) #模拟工作过程
print 'Billy done his work!\n'
print 'lock2 release!'
lock.release() #完成工作,打开锁
def main():
print '***** main *****\n'
lock1=thread.allocate_lock() #申请一个线程锁
lock2=thread.allocate_lock()
lock1.acquire() #把每个线程锁锁上
lock2.acquire()
thread.start_new_thread(work_one,(lock1,))
thread.start_new_thread(work_two,(lock2,))
while lock1.locked(): #检查锁是否打开
pass
while lock2.locked():
pass
print '***** all work done! *****\n'
if __name__ == '__main__':
main()
效果图如下:
2.创建threading模块中的Thread类实现多线程
这个模块是高层模块,使用起来相对于thread模块更方便一些。
先实例化一个Thread对象,传入work_one和work_two函数,在调用start方法,启动线程。最后用join方法,等待线程退出。
import threading
from time import sleep
def work_one():
print 'John starts to work!\n'
sleep(4) #模拟工作过程
print 'John done his work!\n'
def work_two():
print 'Billy starts to work!\n'
sleep(6) #模拟工作过程
print 'Billy done his work!\n'
def main():
print '***** main *****\n'
thread1=threading.Thread(target=work_one) #创建一个Thread实例
thread2=threading.Thread(target=work_two)
thread1.start() #start函数,启动线程
thread2.start()
thread1.join() #join函数,用于等待线程结束
thread2.join()
print '***** all work done! *****\n'
if __name__ == '__main__':
main()
3.继承Thread类,创建子类实例
编写一个MyThread类,继承,并覆盖run方法。然后再调用start和join方法。
import threading
from time import sleep
class Mythread(threading.Thread):
def __init__(self,time,name):
threading.Thread.__init__(self)
self.time=time
self.name=name
def run(self):
sleep(self.time) #模拟工作过程
def main():
print '***** main *****'
thread1=Mythread(4,'John') #创建一个Thread实例
thread2=Mythread(6,'Billy')
print thread1.name,'starts to work!'
thread1.start() #start函数,启动线程
print thread2.name,'starts to work!'
thread2.start()
thread1.join() #join函数,用于等待线程结束
print thread1.name,'done his work!'
thread2.join()
print thread2.name,'done his work!'
print '***** all work done! *****\n'
if __name__ == '__main__':
main()
效果图如下:
