how to make a thread-safe global counter in python

前端 未结 2 419
面向向阳花
面向向阳花 2020-12-15 22:07

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 acces

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 22:36

    Not sure if you have tried this specific syntax already, but for me this has always worked well:

    Define a global lock:

    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
    

提交回复
热议问题