将一个类变量与多个线程同步

时间:2019-11-21 11:04:00

标签: python multithreading synchronization python-decorators class-variables

我正在尝试创建一个装饰器,该装饰器将全局验证请求存储桶是否已满。 铲斗尺寸为40,泄漏率为每秒2。 我希望能够在维护bucker sub 40的同时线程化不同请求的多个实例。self.bucket_current怎么可能变为负数?另外,如何调试这些线程及其作用?

from time import sleep
from concurrent.futures import ThreadPoolExecutor
from math import ceil

class Counter:
    def __init__(self):
        self.bucket_size = 40
        self.bucket_current = 0
        self.bucket_leak_rate = 2


    def countdown(self, secs):
        self.bucket_current += secs
        print(self.bucket_current)
        r = ceil(self.bucket_current/self.bucket_leak_rate)
        sleep(1)
        while self.bucket_current > 0:
            for _ in range(1, r+1):
                if self.bucket_current != 1:
                    self.bucket_current -= 2
                else:
                    self.bucket_current -= 1

                print(self.bucket_current)
                sleep(1)


c = Counter()

with ThreadPoolExecutor() as executor:
    executor.submit(c.countdown, 9)
    sleep(3)
    executor.submit(c.countdown, 7)

输出:

9
7
5
3
10
8
6
4
2
0
-2
-4
-6
-8
-10
-12
-14

1 个答案:

答案 0 :(得分:0)

  

self.bucket_current怎么可能变为负值?

对此的答案是,根据您的代码,在第一行executor.submit(c.countdown, 9)之后,该线程将单独执行,并且在3秒(sleep(3))之后,另一个线程将加入执行{{1} },这两个线程之间没有任何同步。

您需要提供一种同步这两个线程的机制,这是我有时使用的简单装饰器:

executor.submit(c.countdown, 7)