Python多线程基础(转)
Python多线程编程,当程序需要同时并发处理多个任务时,就需要要使用多线程编程。
继承线程类threading.thread,再重载成员函数run,程序处理的代码写在函数run中,最后再调用start()方法来运行线程,而join()方法可以用来等待线程结束。
多线程的资源同步,可使用thread.RLock()来创建资源锁,然后使用acquire()来锁住资源,release()来释放资源。等待事件用thread.Event(),用wait()来等待事件,set()来激发事件,clear()用于清除已激发事件。
关于进程线程的知识有一片很有趣的文章可以帮助你很容易的了解有关进程和线程的知识
当然这只是粗浅的解释,还需要进一步的了解
# 例:多线程编程
1 #!/usr/bin/env python 2 #thread_example2.py 3 import threading 4 import time 5 class timer(threading.Thread): #我的timer类继承自threading.Thread类 6 def __init__(self,no,interval): 7 #在我重写__init__方法的时候要记得调用基类的__init__方法 8 threading.Thread.__init__(self) 9 self.no=no 10 self.interval=interval 11 12 def run(self): #重写run()方法,把自己的线程函数的代码放到这里 13 i = 4 14 while i > 0: 15 print(i) 16 print('Thread Object (%d), Time:%s'%(self.no,time.ctime())) 17 time.sleep(self.interval) 18 i = i - 1 19 20 def test(): 21 threadone=timer(1,1) #产生2个线程对象 22 threadtwo=timer(2,3) 23 threadone.start() #通过调用线程对象的.start()方法来激活线程 24 threadtwo.start() 25 26 if __name__=='__main__': 27 test()