python-麪包店算法實現多線程鎖

#coding: UTF-8
import threading
import time
import random

# 麪包店算法實現線程鎖

# 爭奪的資源
incNum = 0

class BakeryLock:
    def __init__(self, threadCount):
        # 取得的號碼
        self.number = [0 for _ in range(threadCount)]
        # 是否正在取號
        self.entering = [False for _ in range(threadCount)]

    def lock(self, threadNum):
        # 進入麪包店,準備取號
        self.entering[threadNum] = True
        # 取號
        self.number[threadNum] = max(self.number) + 1
        # 取號結束
        self.entering[threadNum] = False

        # 等待前面的顧客買麪包結束
        for i in range(threadCount):
            # 等待顧客i取號結束
            while self.entering[i] :
                pass
            # 等待前面的顧客i買麪包結束
            # 判斷顧客i是否在自己前面的條件:顧客i取的號碼比自己小,如果取的號碼相同,那麼線程id小的優先
            while (self.number[i]!=0) and ((self.number[i], i) < (self.number[threadNum], threadNum)):
                pass

    def unlock(self, threadNum):
        self.number[threadNum] = 0
    
# 使用資源
def achive_resource(threadNum):
    print('Now is no.{} thread achive the resource'.format(threadNum))
    global incNum
    incNum += 1

def start_request(threadNum, bkLock):
    iLoopCount = 0
    while iLoopCount<5:
        bkLock.lock(threadNum)
        achive_resource(threadNum)
        bkLock.unlock(threadNum)
        iLoopCount+=1

if __name__=='__main__':
    threadCount = 100
    bkLock = BakeryLock(threadCount)

    threads = []
    for i in range(threadCount):
        t = threading.Thread(target=start_request, args=(i, bkLock,))
        t.start()
        threads.append(t)
    
    for i in range(threadCount):
        threads[i].join()

    print(incNum)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章