Semaphore訊號量,semaphore訊號

來源:互聯網
上載者:User

Semaphore訊號量,semaphore訊號
一、前言

  互斥鎖 同時只允許一個線程更改資料,而Semaphore是同時允許一定數量的線程更改資料 ,比如廁所有3個坑,那最多隻允許3個人上廁所,後面的人只能等裡面有人出來了才能再進去。

二、semaphore

  訊號量semaphore,是一個變數,控制著對公用資源或者臨界區的訪問。訊號量維護著一個計數器,指定可同時訪問資源或者進入臨界區的線程數。 每次有一個線程獲得訊號量時,計數器-1。若計數器為0,其他線程就停止訪問訊號量,直到另一個線程釋放訊號量。每當調用acquire()時,內建計數器-1 每當調用release()時,內建計數器+1。

# -*- coding: UTF-8 -*-import threadingimport timeclass MyThread(threading.Thread):    def run(self):        global num        semaphore.acquire()  # 擷取訊號鎖        lock.acquire()        num += 1        print('run the thread: %s\n' % self.name)        print('now the number is ', num)        lock.release()        time.sleep(1)        semaphore.release()  # 釋放訊號鎖num = 0lock = threading.Lock()# 最多允許5個線程同時運行semaphore = threading.BoundedSemaphore(5)if __name__ == '__main__':    for i in range(17):        t = MyThread()        t.start()    while threading.active_count() != 1:        pass    else:        print('--all threads done---')        print(num)

  註:

  • 程式運行看上去是5個一組啟動並執行,其實如果有個線程先完成了,釋放了訊號量,等待的線程就能擷取訊號量,但不超過5個。
  • 多個線程同時運行,還是會有安全執行緒問題,所以對共用資源競爭還是要加鎖
三、使用情境 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.