使用threading的Condition实现线程调度

在多个线程之间可以使用threading模块的Condition方法进行资源调度,如下所示:

import time
import threading
from concurrent.futures import ThreadPoolExecutor
import random


class Account:
    """银行账户"""

    def __init__(self):
        self.balance = 0
        lock = threading.RLock()
        self.condition = threading.Condition(lock)  # 重点

    def deposit(self, money):
        with self.condition:  # 重点
            new_balance = self.balance + money
            time.sleep(0.01)
            self.balance = new_balance
            self.condition.notify_all()  # 重点

    def withdraw(self, money):
        """取钱"""
        with self.condition: # 重点
            while money > self.balance:
                self.condition.wait()  # 重点
            new_balance = self.balance - money
            time.sleep(0.01)
            self.balance = new_balance


def add_money(account):
    while True:
        money = random.randint(5, 10)
        account.deposit(money)
        print(threading.current_thread().name,
              ':', money, '====>', account.balance)
        time.sleep(1)


def sub_money(account):
    while True:
        money = random.randint(10, 30)
        account.withdraw(money)
        print(threading.current_thread().name,
              ':', money, '<====', account.balance)
        time.sleep(2)


account = Account()
with ThreadPoolExecutor(max_workers=15) as pool:
    for _ in range(5):
        pool.submit(add_money, account)
    for _ in range(10):
        pool.submit(sub_money, account)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容