简体   繁体   English

如何使每个线程的全局计数器增量?

[英]How do I make a global counter increment with each thread?

I am trying to make a python file that will increment a global counter by 5 for every time a thread is started.我正在尝试制作一个 python 文件,该文件将在每次启动线程时将全局计数器增加 5。 My goal is to have 4 threads increment the counter by 5 and the end result is 20. Here is the code I have so far:我的目标是让 4 个线程将计数器增加 5,最终结果为 20。这是我到目前为止的代码:

    import threading
    import time
    global counter
    counter =0
    class MyThread(threading.Thread):
        counter = counter
        def __init__(self, name, delay, counter=0):
            threading.Thread.__init__(self)
            self.name = name
            self.delay = delay
            self.counter = counter

        def run(self):
    
            print('Starting thread %s...'% self.name)
            self.thread_lock.acquire()
            self.thread_lock.release()
            print('Finished thread %s...'% self.name)


        thread_lock = threading.Lock()

    thread1 = MyThread('A', 0.1)
    thread2 = MyThread('B', 0.1)
    thread3 = MyThread('C', 0.1)
    thread4 = MyThread('D', 0.1)

    thread1.start()
    thread2.start()
    thread3.start()
    thread4.start()

    thread1.join()
    thread2.join()
    thread3.join()
    thread4.join()

You could use a counter class and a (locking) function that increases the value:您可以使用计数器 class 和(锁定)function 来增加值:

import threading
import time

lock = threading.Lock()


class Counter:
    def __init__(self, initial_count):
        self.value = initial_count


def add(counter, name, delay, value):
    with lock:
        msg = f"{name} is sleeping for {delay} seconds, before increasing {counter.value} by {value}"
        print(msg)
        time.sleep(x)
        counter.value = counter.value + value


counter = Counter(0)
increasingValue = 5

_threads = []
for x in range(4):
    th = threading.Thread(
        target=add, args=(counter, f"thread_{x}", x, increasingValue)
    )
    _threads.append(th)
    th.start()
    [t.join() for t in _threads]

print('>', counter.value)

Out:出去:

thread_0 is sleeping for 0 seconds, before increasing 0 by 5
thread_1 is sleeping for 1 seconds, before increasing 5 by 5
thread_2 is sleeping for 2 seconds, before increasing 10 by 5
thread_3 is sleeping for 3 seconds, before increasing 15 by 5
> 20

You have many counter variables in your program您的程序中有许多counter变量

counter =0

creates one in the global namespace在全局命名空间中创建一个

class MyThread(threading.Thread):
    counter = counter

creates another in the class namespace在 class 命名空间中创建另一个

    def __init__(self, name, delay, counter=0):
        ...
        self.counter = counter

creates one in each instance of your thread class.在您的线程 class 的每个实例中创建一个。 And you don't actually increment any of them.而且你实际上并没有增加它们中的任何一个。

If you really want a single global counter, use the global keyword in the method that increments it.如果您真的想要一个全局计数器,请在递增它的方法中使用global关键字。 global tells a function that a variable should be resolved in the global namespace, not the local function namespace. global告诉 function 变量应该在全局命名空间中解析,而不是本地 function 命名空间。 Its completely unneeded at the module level, you can't unilaterally declare a variable global.它在模块级别完全不需要,您不能单方面声明一个全局变量。 You can only tell specific functions how to treat the variable.您只能告诉特定函数如何处理变量。

import threading
import time

counter =0
class MyThread(threading.Thread):

    def __init__(self, name, delay, counter=0):
        threading.Thread.__init__(self)
        self.name = name
        self.delay = delay

    def run(self):
        global counter    
        print('Starting thread %s...'% self.name)
        self.thread_lock.acquire()
        counter += 5
        self.thread_lock.release()
        print('Finished thread %s...'% self.name)


    thread_lock = threading.Lock()

thread1 = MyThread('A', 0.1)
thread2 = MyThread('B', 0.1)
thread3 = MyThread('C', 0.1)
thread4 = MyThread('D', 0.1)

thread1.start()
thread2.start()
thread3.start()
thread4.start()

thread1.join()
thread2.join()
thread3.join()
thread4.join()

print(counter)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM