Python多線程學習(線程使用)
一.創建線程
1.通過thread模塊中的start_new_thread(func,args)創建線程:
在Eclipse+pydev中敲出以下代碼:
# -*- coding: utf-8 -*-
import thread
def run_thread(n):
for i in range(n):
print i
thread.start_new_thread(run_thread,(4,)) #參數一定是元組,兩個參數可以寫成(a,b)
運行報錯如下:
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
網上查出原因是不建議使用thread,然後我在pythonGUI中做了測試,測試結果如下,顯然python是支持thread創建多線程的,在pydev中出錯原因暫時不明。
>>> import thread
>>> def run(n):
for i in range(n):
print i
>>> thread.start_new_thread(run,(4,))
98520
1
>>>
2
3
2.通過繼承threading.Thread創建線程,以下示例創建了兩個線程
# -*- coding: utf-8 -*-
'''''
Created on 2012-8-8
@author: jeromewei
'''
from threading import Thread
import time
class race(Thread):
def __init__(self,threadname,interval):
Thread.__init__(self,name=threadname)
self.interval = interval
self.isrunning = True
def run(self): #重寫threading.Thread中的run()
while self.isrunning:
print 'thread %s is running,time:%s\n' %(self.getName(),time.ctime()) #獲得線程的名稱和當前時間
time.sleep(self.interval)
def stop(self):
self.isrunning = False
def test():
thread1 = race('A',1)
thread2 = race('B',2)
thread1.start()
thread2.start()
time.sleep(5)
thread1.stop()
thread2.stop()
if __name__ =='__main__':
test()
3. 在threading.Thread中指定目標函數作爲線程處理函數
# -*- coding: utf-8 -*-
from threading import Thread
def run_thread(n):
for i in range(n):
print i
t1 = Thread(target=run_thread,args=(5,))#指定目標函數,傳入參數,這裏參數也是元組
t1.start() #啓動線程
二. threading.Thread中常用函數說明
函數名 | 功能 |
run() | 如果採用方法2創建線程就需要重寫該方法 |
getName() | 獲得線程的名稱(方法2中有示例) |
setName() | 設置線程的名稱 |
start() | 啓動線程 |
join(timeout) | 在join()位置等待另一線程結束後再繼續運行join()後的操作,timeout是可選項,表示最大等待時間 |
setDaemon(bool) | True:當父線程結束時,子線程立即結束;False:父線程等待子線程結束後才結束。默認爲False |
isDaemon() | 判斷子線程是否和父線程一起結束,即setDaemon()設置的值 |
isAlive() | 判斷線程是否在運行 |
以上方法中,我將對join()和setDaemon(bool)作着重介紹,示例如下:
(1)join方法:
# -*- coding: utf-8 -*-
import threading
import time #導入time模塊
class Mythread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
time.sleep(2)
for i in range(5):
print '%s is running····'%self.getName()
t2 = Mythread('B')
t2.start()
#t2.join()
for i in range(5):
print 'the program is running···'
這時的程序流程是:主線程先運行完,然後等待B線程運行,所以輸出結果爲:
the program is running···
the program is running···
the program is running···
B is running····
B is running····
B is running····
如果啓用t2.join() ,這時程序的運行流程是:當主線程運行到 t2.join() 時,它將等待 t2 運行完,然後再繼續運行t2.join() 後的操作,呵呵,你懂了嗎,所以輸出結果爲:
B is running····
B is running····
B is running····
the program is running···
the program is running···
the program is running···
(2)setDaemon方法:
# -*- coding: utf-8 -*-
import threading
import time
class myThread(threading.Thread):
def __init__(self, threadname):
threading.Thread.__init__(self, name=threadname)
def run(self):
time.sleep(5)
print '%s is running·······done'%self.getName()
t=myThread('son thread')
#t.setDaemon(True)
t.start()
if t.isDaemon():
print "the father thread and the son thread are done"
else:
print "the father thread is waiting the son thread····"
這段代碼的運行流程是:主線程打印完最後一句話後,等待son thread 運行完,然後程序才結束,所以輸出結果爲:
the father thread is waitting the son thread····
son thread is running·······done
如果啓用t.setDaemon(True) ,這段代碼的運行流程是:當主線程打印完最後一句話後,不管 son thread 是否運行完,程序立即結束,所以輸出結果爲:
the father thread and the son thread are done
三. 小結
介紹到這裏,python多線程使用級別的知識點已全部介紹完了,下面我會分析一下python多線程的同步問題。