如何在python中创建线程安全的全局计数器 [英] how to make a thread-safe global counter in python
问题描述
我正在创建一个threading.Timer(2,work)
运行线程.在每个工作函数内部,在某些情况下,全局计数器必须递增而不会产生冲突,以便在产生的工作线程之间访问计数器变量.
I'm creating a threading.Timer(2,work)
run threads. Inside each work function, upon some condition the global counter must increment without conflict for access of counter variable among the spawned work threads.
我尝试了Queue.Queue
分配的计数器以及threading.Lock()
.这是实现线程安全的全局增量变量的最佳方法.
I've tried Queue.Queue
assigned counter as well as threading.Lock()
. Which is a best way to implement thread-safe global increment variable.
以前有人在这里问过一个问题: Python线程.如何锁定线程?
Previously someone asked question here: Python threading. How do I lock a thread?
推荐答案
不确定您是否已经尝试过此特定语法,但对我而言,它一直运行良好:
Not sure if you have tried this specific syntax already, but for me this has always worked well:
定义全局锁:
import threading
threadLock = threading.Lock()
然后,每次在各个线程中增加计数器时,您都必须获取并释放锁:
and then you have to acquire and release the lock every time you increase your counter in your individual threads:
with threadLock:
global_counter += 1
这篇关于如何在python中创建线程安全的全局计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!