線程、鎖、遞迴鎖、訊號量,遞迴訊號

來源:互聯網
上載者:User

線程、鎖、遞迴鎖、訊號量,遞迴訊號

線程的直接調用:

import threading   #直接調用def run2(n):      #函數名可以隨便起    n = '吞噬者'    print('rhread %s is start'% n)t = threading.Thread(target=run2,args='n')   #產生一個線程執行個體t.start()

 

線程的繼承式調用:

import threading      #繼承式調用class Mythreading(threading.Thread):    def __init__(self,n):        super(Mythreading,self).__init__()    #重寫構造方法,繼承基類        self.n = n    def run(self):              #函數名必須是 run        print('線程 %s 已啟動' % self.n)t = Mythreading('吞噬者')t.run()

 

鎖:

import threading,timenumber = 0def run2(n):  #定義每個線程要啟動並執行函數    lock.acquire()    #在修改資料之前加鎖,加鎖之後,程式立刻變成串列    global number    number += 1    time.sleep(1)    lock.release()    #修改結束釋放鎖   以此來避免重複修改資料(這種情況只會在2.x中出現,3.xzhong1不會重複修改,可以理解為3.x自己將這一塊兒最佳化了,但是還是得加鎖)    print('線程啟動:',n,threading.current_thread(),threading.active_count())    #threading.current_thread()顯示線程類型,是主線程還是子線程    #threading.active_count()   顯示當前活躍的線程數    print('線程執行結束')lock = threading.Lock()             #申請一把鎖t_objs = []                         #用來存線程執行個體std = time.time()for i in range(100):    t = threading.Thread(target=run2,args=('t - %s' % i,))    # t.setDaemon(True)               #將當前線程變成守護線程    t.start()    t_objs.append(t)                #為了不阻塞後麵線程的啟動,不在這兒join(等待),先放在一個列表裡for a in t_objs:                    #迴圈線程執行個體列表,等待所有線程執行完畢    a.join()   #等待print(time.time() - std)print('num:',number)print('全部結束了',threading.current_thread(),threading.active_count())

 

訊號量:

#Author:SSimport threading,time   #每次最多5個線程同時運行def run(n):    semaphore.acquire()       #加訊號量    time.sleep(1)    print('run the thread: %s\n' % n)    semaphore.release()       #釋放semaphore = threading.BoundedSemaphore(5) #申請訊號量 最多允許5個線程同時運行for i in range(20):    t = threading.Thread(target=run,args=(i,))    t.start()while threading.active_count() != 1:    passelse:    print('線程全部結束!')

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.