使用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)

你可能感兴趣的:(使用threading的Condition实现线程调度)