傳統的python單執行緒程式:
''' created on 2012-3-9 @author: administrator ''' #!/usr/bin/env python from time import sleep,ctime def loop0(): print 'start loop0 at:',ctime() sleep(4) print 'loop0 done at:',ctime() def loop1(): print 'start loop1 at:',ctime() sleep(2) print 'loop1 done at:',ctime() def main(): print 'start at:',ctime() loop0() loop1() print 'all done at:',ctime() if __name__=='__main__': main()執行結果:
start at: fri mar 09 16:28:12 2012 start loop0 at: fri mar 09 16:28:12 2012 loop0 done at: fri mar 09 16:28:16 2012 start loop1 at: fri mar 09 16:28:16 2012 loop1 done at: fri mar 09 16:28:18 2012 all done at: fri mar 09 16:28:18 2012 可見程式是順序執行。
多執行緒例子:
'''
created on 2012-3-9
@author: administrator
'''#!/usr/bin/env python
import thread
from time import sleep,ctime
def loop0():
print 'start loop0 at:',ctime()
sleep(4)
print 'loop0 done at:',ctime()
def loop1():
print 'start loop1 at:',ctime()
sleep(2)
print 'loop1 done at:',ctime()
def main():
print 'start at:',ctime()
thread.start_new_thread(loop0, ())
thread.start_new_thread(loop1, ())
sleep(6)
print 'all done at:',ctime()
if __name__=='__main__':
main()
執行結果:
start at: fri mar 09 16:35:27 2012 start loop0 at: fri mar 09 16:35:27 2012 start loop1 at: fri mar 09 16:35:27 2012 loop1 done at: fri mar 09 16:35:29 2012 loop0 done at: fri mar 09 16:35:31 2012 all done at: fri mar 09 16:35:33 2012可見loop0 的執行和
loop1是並行的,一共三個執行緒:主線程、執行loop0的執行緒和執行loop1的執行緒。
Python 多執行緒程式設計 一
userrequestthread 負責讀取客戶端輸入,該輸入可能來自 i o 通道,程式將建立多個執行緒,每個客戶端乙個,客戶端的請求將會被放入佇列中 requestprocessor 該執行緒負責從佇列中獲取請求並進行處理,為第3個執行緒提供輸出 replythread 負責向使用者輸出,將結果...
python多執行緒程式設計(一)
python提供兩個模組支援多執行緒程式設計 thread和threading。thread模組函式 函式描述 start new thread function,args,kwargs none 產生乙個新執行緒,在新執行緒中用指定引數和可選的kwargs呼叫function函式 allocate...
python 多執行緒程式設計
一 執行緒基礎 1 建立執行緒 thread模組提供了start new thread函式,用以建立執行緒。start new thread函式成功建立後還可以對其進行操作。其函式原型 start new thread function,atgs kwargs 其引數含義如下 args 元組形式的引...