python避免死結方法執行個體分析

來源:互聯網
上載者:User
本文執行個體講述了python避免死結方法。分享給大家供大家參考。具體分析如下:

當兩個或者更多的線程在等待資源的時候就會產生死結,兩個線程相互等待。
在本文執行個體中 thread1 等待thread2釋放block , thread2等待thtead1釋放ablock,

避免死結的原則:

1. 一定要以一個固定的順序來取得鎖,這個列子中,意味著首先要取得alock, 然後再去block

2. 一定要按照與取得鎖相反的順序釋放鎖,這裡,應該先釋放block,然後是alock

import threading ,timea = 5alock = threading.Lock()b = 5block = threading.Lock()def thread1calc():  print "thread1 acquiring lock a"  alock.acquire()  time.sleep(5)  print "thread1 acquiring lock b"  block.acquire()  a+=5  b+=5  print "thread1 releasing both locks"  block.release()  alock.release()def thread2calc():  print "thread2 acquiring lock b"  block.acquire()  time.sleep(5)  print "thread2 acquiring lock a"  alock.acquire()  time.sleep(5)  a+=10  b+=10  print "thread2 releasing both locks"  block.release()  alock.release()t = threading.Thread(target = thread1calc)t.setDaemon(1)t.start()t = threading.Thread(target = thread2calc)t.setDaemon(2)t.start()while 1:  time.sleep(300)

輸出:

thread1 acquiring lock athread2 acquiring lock bthread1 acquiring lock bthread2 acquiring lock a

希望本文所述對大家的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.