python多線程threading.Lock鎖用法執行個體_python

來源:互聯網
上載者:User

本文執行個體講述了python多線程threading.Lock鎖的用法執行個體,分享給大家供大家參考。具體分析如下:

python的鎖可以獨立提取出來

複製代碼 代碼如下:
mutex = threading.Lock()
#鎖的使用
#建立鎖
mutex = threading.Lock()
#鎖定
mutex.acquire([timeout])
#釋放
mutex.release()

鎖定方法acquire可以有一個逾時時間的選擇性參數timeout。如果設定了timeout,則在逾時後通過傳回值可以判斷是否得到了鎖,從而可以進行一些其他的處理。

複製代碼 代碼如下:
#!/usr/bin/env python
#coding=utf-8
import threading
import time
 
class MyThread(threading.Thread):
    def run(self):
        global num
        time.sleep(1)
 
        if mutex.acquire(1): 
            num = num+1
            msg = self.name+' set num to '+str(num)
            print msg
            mutex.release()
num = 0
mutex = threading.Lock()
def test():
    for i in range(5):
        t = MyThread()
        t.start()
if __name__ == '__main__':
    test()
Thread-1 set num to 1
Thread-3 set num to 2
Thread-4 set num to 3
Thread-5 set num to 4
Thread-2 set num to 5

希望本文所述對大家的Python程式設計有所協助。

聯繫我們

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