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)

 

你可能感兴趣的:(分布式)