Python中如果要使用線程的話,python的lib中提供了兩種方式。
一種是函數式,
一種是用類來包裝的線程對象。
舉兩個簡單的例子希望起到拋磚引玉的作用,關於多線程編程的其他知識例如互斥、信號量、臨界區等請參考python的文檔及相關資料。
1、調用thread模塊中的start_new_thread()函數來產生新的線程,請看代碼:
### thread_example.py
import time
import thread
def timer(no,interval): #自己寫的線程函數
while True:
print 'Thread :(%d) Time:%s'%(no,time.ctime())
time.sleep(interval)
def test():#使用thread.start_new_thread()來產生2個新的線程
thread.start_new_thread(timer,(1,1))
thread.start_new_thread(timer,(2,3))
if__name__=='__main__':
test()
這個是 thread.start_new_thread(function,args[,kwargs]) 函數原型,其中function參數是你將要調用的線程函數;args是講傳遞給你的線程函數的參數,他必須是個tuple類型;而kwargs是可選的參數。線程的結束一般依靠線程函數的自然結束;也可以在線程函數中調用thread.exit(),他拋出SystemExit exception,達到退出線程的目的。
2、通過調用threading模塊繼承threading.Thread類來包裝一個線程對象。請看代碼
### threading_example.py
import threading
import time
# 我的timer類繼承自threading.Thread類
class timer(threading.Thread):
# 在我重寫__init__方法的時候要記得調用基類的__init__方法
def __init__(self, no, interval):
threading.Thread.__init__(self)
self.no = no
self.interval = interval
# 重寫run()方法,把自己的線程函數的代碼放到這裏
def run(self):
while True:
print 'Thread Object (%d), Time:%s'%(self.no, time.ctime())
time.sleep(self.interval)
def test():
# 產生2個線程對象
threadone = timer(1, 1)
threadtwo = timer(2, 3)
# 通過調用線程對象的.start()方法來激活線程
threadone.start()
threadtwo.start()
# main test
if name__=='__main__':
test()
其實thread和threading的模塊中還包含了其他的很多關於多線程編程的東西,例如鎖、定時器、獲得激活線程列表等等,請大家仔細參考python的文檔!另外,線程還有退出的問題,這可以有很多種解決方法, 如事件,信號通知等。
下面是一個帶事件的線程:
####
import sys
import time
import thread
import threading
e1 = threading.Event()
e2 = threading.Event()
def timer1(no, interval):
exit_count = 0
while True:
print 'Thread:(%d) Time:%s' % (no, time.ctime())
time.sleep(interval)
exit_count = exit_count + 1
if exit_count == 10:
e1.set()
break
print 'end thread -- %d' %( no, )
def timer2(no, interval):
while True:
print 'Thread:(%d) Time:%s' % (no, time.ctime())
time.sleep(interval)
if e1.isSet():
e2.set()
break
print 'end thread -- %d' % ( no, )
def test():
thread.start_new_thread(timer1, (1, 1))
thread.start_new_thread(timer2, (2, 3))
##
e1.wait()
e2.wait()
print('End test.')
#
if __name__ == '__main__':
test()