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

首頁(yè) > 編程 > Python > 正文

python實(shí)現(xiàn)多線程的兩種方式

2019-11-25 16:47:04
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

目前python 提供了幾種多線程實(shí)現(xiàn)方式 thread,threading,multithreading ,其中thread模塊比較底層,而threading模塊是對(duì)thread做了一些包裝,可以更加方便的被使用。
2.7版本之前python對(duì)線程的支持還不夠完善,不能利用多核CPU,但是2.7版本的python中已經(jīng)考慮改進(jìn)這點(diǎn),出現(xiàn)了multithreading  模塊。threading模塊里面主要是對(duì)一些線程的操作對(duì)象化,創(chuàng)建Thread的class。一般來(lái)說(shuō),使用線程有兩種模式:

A 創(chuàng)建線程要執(zhí)行的函數(shù),把這個(gè)函數(shù)傳遞進(jìn)Thread對(duì)象里,讓它來(lái)執(zhí)行;
B 繼承Thread類(lèi),創(chuàng)建一個(gè)新的class,將要執(zhí)行的代碼 寫(xiě)到run函數(shù)里面。

本文介紹兩種實(shí)現(xiàn)方法。
第一種 創(chuàng)建函數(shù)并且傳入Thread 對(duì)象中
t.py 腳本內(nèi)容

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()

 thclass.py 腳本內(nèi)容:

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()

以上就是本文的全部?jī)?nèi)容嗎,希望對(duì)大家學(xué)習(xí)python程序設(shè)計(jì)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 昌邑市| 张掖市| 阿克陶县| 陵水| 长治县| 神农架林区| 乐陵市| 永宁县| 七台河市| 德化县| 吉安市| 望江县| 卓资县| 怀仁县| 江都市| 饶河县| 元江| 九江市| 杭锦后旗| 晋江市| 麦盖提县| 博白县| 张家口市| 吉安市| 珠海市| 新源县| 遵化市| 剑河县| 新竹县| 青阳县| 桃园县| 泌阳县| 陵川县| 黔西县| 南澳县| 余庆县| 金川县| 普兰县| 宝坻区| 元谋县| 濮阳市|