欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python 多線程的實(shí)例詳解

 更新時(shí)間:2017年09月07日 15:34:48   作者:攻城獅--晴明  
這篇文章主要介紹了 Python 多線程的實(shí)例詳解的相關(guān)資料,希望通過(guò)本文大家能掌握多線程的知識(shí),需要的朋友可以參考下

 Python 多線程的實(shí)例詳解

一)線程基礎(chǔ)

1、創(chuàng)建線程:

thread模塊提供了start_new_thread函數(shù),用以創(chuàng)建線程。start_new_thread函數(shù)成功創(chuàng)建后還可以對(duì)其進(jìn)行操作。
其函數(shù)原型:

  start_new_thread(function,atgs[,kwargs])

其參數(shù)含義如下:

    function: 在線程中執(zhí)行的函數(shù)名
    args:元組形式的參數(shù)列表。
    kwargs: 可選參數(shù),以字典的形式指定參數(shù)

方法一:通過(guò)使用thread模塊中的函數(shù)創(chuàng)建新線程。

>>> import thread 
>>> def run(n): 
  for i in range(n): 
    print i 
 
     
>>> thread.start_new_thread(run,(4,))  #注意第二個(gè)參數(shù)一定要是元組的形式 
53840 
 
 
1 
>>>  
2 
3 
KeyboardInterrupt 
>>> thread.start_new_thread(run,(2,)) 
17840 
 
 
1 
>>>  
thread.start_new_thread(run,(),{'n':4}) 
39720 
 
 
1 
>>>  
2 
3 
thread.start_new_thread(run,(),{'n':3}) 
32480 
 
 
1 
>>>  
2 

方法二:通過(guò)繼承threading.Thread創(chuàng)建線程

>>> import threading 
>>> class mythread(threading.Thread): 
  def __init__(self,num): 
    threading.Thread.__init__(self) 
    self.num = num 
  def run(self):        #重載run方法 
    print 'I am', self.num 
 
     
>>> t1 = mythread(1) 
>>> t2 = mythread(2) 
>>> t3 = mythread(3) 
>>> t1.start()      #運(yùn)行線程t1 
I am 
>>> 1 
t2.start() 
I am 
>>> 2 
t3.start() 
I am 
>>> 3 

方法三:使用threading.Thread直接在線程中運(yùn)行函數(shù)。

import threading 
>>> def run(x,y): 
  for i in range(x,y): 
    print i 
 
>>> t1 = threading.Thread(target=run,args=(15,20)) #直接使用Thread附加函數(shù)args為函數(shù)參數(shù) 
 
>>> t1.start() 
15 
>>>  
16 
17 
18 
19 

二)Thread對(duì)象中的常用方法:

1、isAlive方法:

>>> import threading 
>>> import time 
>>> class mythread(threading.Thread): 
  def __init__(self,id): 
    threading.Thread.__init__(self) 
    self.id = id 
  def run(self): 
    time.sleep(5)  #休眠5秒 
    print self.id 
 
     
>>> t = mythread(1) 
>>> def func(): 
  t.start() 
  print t.isAlive()  #打印線程狀態(tài) 
 
   
>>> func() 
True 
>>> 1 

2、join方法:

原型:join([timeout]) 

    timeout: 可選參數(shù),線程運(yùn)行的最長(zhǎng)時(shí)間

import threading 
>>> import time   #導(dǎo)入time模塊 
>>> class Mythread(threading.Thread): 
  def __init__(self,id): 
    threading.Thread.__init__(self) 
    self.id = id 
  def run(self): 
    x = 0 
    time.sleep(20) 
    print self.id 
 
     
>>> def func(): 
  t.start() 
  for i in range(5): 
    print i 
 
     
>>> t = Mythread(2) 
>>> func() 
0 
1 
2 
3 
4 
>>> 2 
def func(): 
  t.start() 
  t.join() 
  for i in range(5): 
    print i 
 
     
>>> t = Mythread(3) 
>>> func() 
3 
0 
1 
2 
3 
4 
>>>  

3、線程名:

>>> import threading 
>>> class mythread(threading.Thread): 
  def __init__(self,threadname): 
    threading.Thread.__init__(self,name=threadname) 
  def run(self): 
    print self.getName() 
 
     
>>>  
>>> t1 = mythread('t1') 
>>> t1.start() 
t1 
>>>  

 4、setDaemon方法

在腳本運(yùn)行的過(guò)程中有一個(gè)主線程,如果主線程又創(chuàng)建了一個(gè)子線程,那么當(dāng)主線程退出時(shí),會(huì)檢驗(yàn)子線程是否完成。如果子線程未完成,則主線程會(huì)在等待子線程完成后退出。

當(dāng)需要主線程退出時(shí),不管子線程是否完成都隨主線程退出,則可以使用Thread對(duì)象的setDaemon方法來(lái)設(shè)置。 

三)線程同步

1.簡(jiǎn)單的線程同步

使用Thread對(duì)象的Lock和RLock可以實(shí)現(xiàn)簡(jiǎn)單的線程同步。對(duì)于如果需要每次只有一個(gè)線程操作的數(shù)據(jù),可以將操作過(guò)程放在acquire方法和release方法之間。如: 

# -*- coding:utf-8 -*- 
import threading 
import time 
class mythread(threading.Thread): 
  def __init__(self,threadname): 
    threading.Thread.__init__(self,name = threadname) 
  def run(self): 
    global x        #設(shè)置全局變量 
#    lock.acquire()     #調(diào)用lock的acquire方法 
    for i in range(3): 
      x = x + 1 
    time.sleep(2) 
    print x 
#    lock.release()     #調(diào)用lock的release方法 
#lock = threading.RLock()    #生成Rlock對(duì)象 
t1 = [] 
for i in range(10): 
  t = mythread(str(i)) 
  t1.append(t) 
x = 0          #將全局變量的值設(shè)為0 
for i in t1:  
  i.start() 
 
E:/study/<a  rel="external nofollow" class='replace_word' title="Python知識(shí)庫(kù)" target='_blank' style='color:#df3434; font-weight:bold;'>Python</a>/workspace>xianchengtongbu.py 
3 
6 
9 
12 
15 
18 
21 
24 
27 
30 

如果將lock.acquire()和lock.release(),lock = threading.Lock()刪除后保存運(yùn)行腳本,結(jié)果將是輸出10個(gè)30。30是x的最終值,由于x是全局變量,每個(gè)線程對(duì)其操作后進(jìn)入休眠狀態(tài),在線程休眠的時(shí)候,Python解釋器就執(zhí)行了其他的線程而是x的值增加。當(dāng)所有線程休眠結(jié)束后,x的值已被所有線修改為了30,因此輸出全部為30。 

2、使用條件變量保持線程同步。

python的Condition對(duì)象提供了對(duì)復(fù)制線程同步的支持。使用Condition對(duì)象可以在某些事件觸發(fā)后才處理數(shù)據(jù)。Condition對(duì)象除了具有acquire方法和release的方法外,還有wait方法、notify方法、notifyAll方法等用于條件處理。

# -*- coding:utf-8 -*- 
import threading 
class Producer(threading.Thread): 
  def __init__(self,threadname): 
    threading.Thread.__init__(self,name = threadname) 
  def run(self): 
    global x 
    con.acquire() 
    if x == 1000000: 
      con.wait() 
    #  pass 
    else: 
      for i in range(1000000): 
        x = x + 1 
      con.notify() 
    print x 
    con.release() 
class Consumer(threading.Thread): 
  def __init__(self,threadname): 
    threading.Thread.__init__(self,name = threadname) 
  def run(self): 
    global x  
    con.acquire() 
    if x == 0: 
      con.wait() 
      #pass 
    else: 
      for i in range(1000000): 
        x = x - 1 
      con.notify() 
    print x  
    con.release() 
con = threading.Condition() 
x = 0 
p = Producer('Producer') 
c = Consumer('Consumer') 
p.start() 
c.start() 
p.join() 
c.join() 
print x 
 
E:/study/python/workspace>xianchengtongbu2.py 
1000000 
0 
0 

線程間通信:

Event對(duì)象用于線程間的相互通信。他提供了設(shè)置信號(hào)、清除信宏、等待等用于實(shí)現(xiàn)線程間的通信。

1、設(shè)置信號(hào)。Event對(duì)象使用了set()方法后,isSet()方法返回真。
2、清除信號(hào)。使用Event對(duì)象的clear()方法后,isSet()方法返回為假。
3、等待。當(dāng)Event對(duì)象的內(nèi)部信號(hào)標(biāo)志為假時(shí),則wait()方法一直等到其為真時(shí)才返回。還可以向wait傳遞參數(shù),設(shè)定最長(zhǎng)的等待時(shí)間。

# -*- coding:utf-8 -*- 
import threading 
class mythread(threading.Thread): 
  def __init__(self,threadname): 
    threading.Thread.__init__(self,name = threadname) 
  def run(self): 
    global event 
    if event.isSet(): 
      event.clear() 
      event.wait()  #當(dāng)event被標(biāo)記時(shí)才返回 
      print self.getName() 
    else: 
      print self.getName() 
      event.set() 
event = threading.Event() 
event.set() 
t1 = [] 
for i in range(10): 
  t = mythread(str(i)) 
  t1.append(t) 
for i in t1: 
  i.start() 

如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝 閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

  • 快速解決Django關(guān)閉Debug模式無(wú)法加載media圖片與static靜態(tài)文件

    快速解決Django關(guān)閉Debug模式無(wú)法加載media圖片與static靜態(tài)文件

    這篇文章主要介紹了快速解決Django關(guān)閉Debug模式無(wú)法加載media圖片與static靜態(tài)文件的操作方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-04-04
  • python中的deque基本用法詳解

    python中的deque基本用法詳解

    Python?中的?deque是一個(gè)低級(jí)別的、高度優(yōu)化的雙端隊(duì)列,對(duì)于實(shí)現(xiàn)優(yōu)雅、高效的Pythonic隊(duì)列和堆棧很有用,這篇文章主要介紹了python中的deque基本用法的相關(guān)資料,需要的朋友可以參考下
    2017-11-11
  • 解決pycharm19.3.3安裝pyqt5找不到designer.exe和pyuic.exe的問(wèn)題

    解決pycharm19.3.3安裝pyqt5找不到designer.exe和pyuic.exe的問(wèn)題

    這篇文章給大家介紹了pycharm19.3.3安裝pyqt5&pyqt5-tools后找不到designer.exe和pyuic.exe以及配置QTDesigner和PyUIC的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2021-04-04
  • Python中pandas庫(kù)sort_values()方法的使用

    Python中pandas庫(kù)sort_values()方法的使用

    最后去看了有關(guān)于 sort_values 的文檔,成功解決先把單詞出現(xiàn)頻次由高往低依次排序,再把頻次相同的情況下的單詞按照 MD5 值排序這個(gè)問(wèn)題,下面通過(guò)本文講解下Python中pandas庫(kù)sort_values()方法的使用,感興趣的朋友一起看看吧
    2023-07-07
  • Python參數(shù)傳遞機(jī)制傳值和傳引用原理詳解

    Python參數(shù)傳遞機(jī)制傳值和傳引用原理詳解

    這篇文章主要介紹了Python參數(shù)傳遞機(jī)制傳值和傳引用原理詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • Python+Matplotlib繪制雙y軸圖像的示例代碼

    Python+Matplotlib繪制雙y軸圖像的示例代碼

    這篇文章主要介紹了如何利用python的matplotlib繪制雙Y軸圖像,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)python的小伙伴們有很好地幫助,需要的朋友可以參考下
    2022-04-04
  • 利用PyTorch實(shí)現(xiàn)VGG16教程

    利用PyTorch實(shí)現(xiàn)VGG16教程

    這篇文章主要介紹了利用PyTorch實(shí)現(xiàn)VGG16教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-06-06
  • 深入理解Python中變量賦值的問(wèn)題

    深入理解Python中變量賦值的問(wèn)題

    在 python 中賦值語(yǔ)句總是建立對(duì)象的引用值,而不是復(fù)制對(duì)象。因此,python 變量更像是指針,而不是數(shù)據(jù)存儲(chǔ)區(qū)域,這點(diǎn)和大多數(shù)語(yǔ)言類似吧,比如 C++、java 等。下面這篇文章主要介紹了Python中變量賦值的問(wèn)題,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-01-01
  • 如何用Python對(duì)數(shù)學(xué)函數(shù)進(jìn)行求值、求偏導(dǎo)

    如何用Python對(duì)數(shù)學(xué)函數(shù)進(jìn)行求值、求偏導(dǎo)

    這篇文章主要介紹了如何用Python對(duì)數(shù)學(xué)函數(shù)進(jìn)行求值、求偏導(dǎo)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • Python實(shí)現(xiàn)字符串與數(shù)組相互轉(zhuǎn)換功能示例

    Python實(shí)現(xiàn)字符串與數(shù)組相互轉(zhuǎn)換功能示例

    這篇文章主要介紹了Python實(shí)現(xiàn)字符串與數(shù)組相互轉(zhuǎn)換功能,結(jié)合具體實(shí)例形式分析了Python字符串與數(shù)組相關(guān)轉(zhuǎn)換功能的相關(guān)實(shí)現(xiàn)技巧與注意事項(xiàng),需要的朋友可以參考下
    2017-09-09

最新評(píng)論