用python进行多线程锁模拟操作

代码语言:python

所属分类:其他

代码描述:用python进行多线程锁模拟操作,注意,在bfwstudio中运行会超时

代码标签: 线程 模拟 操作

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
import threading
import random
import time
 
gMoney = 0
gCondition = threading.Condition()
gTimes = 0
 
 
class Producer(threading.Thread):
    def run(self):
        global gMoney
        global gTimes
        while True:
            gCondition.acquire()
            if gTimes > 10:
                gCondition.release()
                break
            money = random.randint(0, 100)
            gMoney += money
            gTimes += 1
            print('%s赚了%d元钱,总资产为%d元钱' % (threading.current_thread().name, money, gMoney))
            gCondition.notify_all()
            gCondition.release()
            time.sleep(1)
 
 
class Consumer(threading.Thread):
    def run(self):
        global gMoney
        while True:
            gCondition.acquire()
            money = random.randint(0, 100)
            while gMoney < money:
                if gTimes > .........完整代码请登录后点击上方下载按钮下载查看

网友评论0