国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現多線程的兩種方式分析

2020-02-15 22:51:07
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現多線程的兩種方式。分享給大家供大家參考,具體如下:

目前python 提供了幾種多線程實現方式 thread,threading,multithreading ,其中thread模塊比較底層,而threading模塊是對thread做了一些包裝,可以更加方便的被使用。

2.7版本之前python對線程的支持還不夠完善,不能利用多核CPU,但是2.7版本的python中已經考慮改進這點,出現了multithreading  模塊。threading模塊里面主要是對一些線程的操作對象化,創建Thread的class。一般來說,使用線程有兩種模式:

A 創建線程要執行的函數,把這個函數傳遞進Thread對象里,讓它來執行; B 繼承Thread類,創建一個新的class,將要執行的代碼 寫到run函數里面。

本文介紹兩種實現方法。

第一種 創建函數并且傳入Thread 對象中

t.py 腳本內容

import threading,timefrom time import sleep, ctimedef now() : return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )def test(nloop, nsec): print 'start loop', nloop, 'at:', now() sleep(nsec) print 'loop', nloop, 'done at:', now()def main(): print 'starting at:',now() threadpool=[] for i in xrange(10):  th = threading.Thread(target= test,args= (i,2))  threadpool.append(th) for th in threadpool:  th.start() for th in threadpool :  threading.Thread.join( th ) print 'all Done at:', now()if __name__ == '__main__':  main()

執行結果:

starting at: 2018-08-29 09:34:16
start loop 0 at: 2018-08-29 09:34:16
start loop 1 at: 2018-08-29 09:34:16
start loop 2 at: 2018-08-29 09:34:16start loop 3 at: 2018-08-29 09:34:16

start loop 4 start loopat:  52018-08-29 09:34:16
at: 2018-08-29 09:34:16
start loop 6 at: start loop2018-08-29 09:34:16
7 at: 2018-08-29 09:34:16
start loop 8 start loopat: 9  2018-08-29 09:34:16at:
 2018-08-29 09:34:16
looploop 1 done at: 2018-08-29 09:34:18
 0 done at: 2018-08-29 09:34:18
loop 3 done at: 2018-08-29 09:34:18
looploop 5 done at: 2018-08-29 09:34:18
 2 done at: 2018-08-29 09:34:18
loop 4 done at: 2018-08-29 09:34:18
looploop 7 done at: 2018-08-29 09:34:18
 6 done at: 2018-08-29 09:34:18
looploop  98  done at:done at:  2018-08-29 09:34:182018-08-29 09:34:18

all Done at: 2018-08-29 09:34:18

第二種 創建繼承自Thread的類

thclass.py 腳本內容:

import threading , timefrom time import sleep, ctimedef now() : return str(time.strftime('%Y-%m-%d %H:%M:%S' , time.localtime()))class myThread (threading.Thread) : """docstring for myThread""" def __init__(self, nloop, nsec) :  super(myThread, self).__init__()  self.nloop = nloop  self.nsec = nsec def run(self):  print 'start loop', self.nloop, 'at:', ctime()  sleep(self.nsec)  print 'loop', self.nloop, 'done at:', ctime()def main(): thpool = [] print 'starting at:', now() for i in xrange(10):  thpool.append(myThread(i, 2)) for th in thpool:  th.start() for th in thpool:  th.join() print 'all Done at:', now()if __name__ == '__main__':  main()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 陆河县| 丰镇市| 大余县| 开封市| 赞皇县| 梓潼县| 汤阴县| 河东区| 依兰县| 庄河市| 富源县| 师宗县| 岳池县| 洪泽县| 通化县| 乳源| 桂东县| 中山市| 进贤县| 桑植县| 景德镇市| 扶风县| 梧州市| 嘉峪关市| 巢湖市| 永兴县| 新安县| 龙山县| 梅州市| 长汀县| 大埔县| 文登市| 涡阳县| 军事| 罗田县| 双江| 桃源县| 二连浩特市| 华阴市| 渝中区| 江孜县|