一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術(shù)及教程分享平臺(tái)!
分類導(dǎo)航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務(wù)器之家 - 腳本之家 - Python - python實(shí)現(xiàn)多線程的兩種方式

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

2020-08-23 13:53趙浮云的blog Python

這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)多線程的兩種方式,感興趣的朋友可以參考一下

目前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。一般來說,使用線程有兩種模式:

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import threading,time
from time import sleep, ctime
def 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)容:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import threading ,time
from time import sleep, ctime
def 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ì)有所幫助。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日本一二线不卡在线观看 | 午夜私人影院在线观看 | 免费视频一区二区 | 精品无人区乱码1区2区3区免费 | 大乳一级一区二区三区 | 亚洲成人视屏 | 亚洲日本中文字幕天堂网 | 性夜影院午夜看片 | 欧美福利在线播放 | 操操久久| 久久青青草原综合伊人 | 亚洲一区二区福利视频 | 毛片一级免费 | 国色天香社区在线视频免费观看 | zozo日本另类极品 | 色综久久天天综合绕视看 | 99年水嫩漂亮粉嫩在线播放 | 秋霞午夜伦午夜高清福利片 | 亚洲2卡三卡4卡5卡精品 | gay 男同志被捆绑茎 | 国语刺激对白勾搭视频在线观看 | 欧美日韩高清完整版在线观看免费 | 色偷偷91久久综合噜噜噜 | 精品亚洲欧美中文字幕在线看 | 久久久无码精品亚洲欧美 | 91高跟丝袜 | 白丝女榨干蹂躏我 | 手机跑分排行最新排名 | 无限资源在线观看高清 | 四虎影院永久在线 | 99在线免费观看 | 网站色小妹 | 性夜影院午夜看片 | 全色黄大色黄大片爽一次 | 日韩精品在线一区二区 | 天天色国产 | 国产日韩在线 | kkkk4444在线看片免费 | 美女mm131爽爽爽久久 | 欧美视频免费 | 午夜亚洲|