锁定Python中的方法? [英] Locking a method in Python?
问题描述
这是我的问题:我正在使用APScheduler库在应用程序中添加计划的作业.我有多个作业同时执行相同的代码,但参数不同.当这些作业同时访问相同的方法时,就会出现问题,这会导致我的程序无法正常工作.
Here is my problem: I'm using APScheduler library to add scheduled jobs in my application. I have multiple jobs executing same code at the same time, but with different parameters. The problem occurs when these jobs access the same method at the same time which causes my program to work incorrectly.
我想知道Python 3.4中是否有一种方法可以锁定一个方法,以便一次只能有一个线程访问它?如果是这样,请您发布一个简单的示例代码?谢谢.
I wanna know if there is a way to lock a method in Python 3.4 so that only one thread may access it at a time? If so, could you please post a simple example code? Thanks.
推荐答案
您可以使用基本的python锁定机制:
You can use a basic python locking mechanism:
from threading import Lock
lock = Lock()
...
def foo():
lock.acquire()
try:
# only one thread can execute code there
finally:
lock.release() #release lock
或使用上下文管理:
def foo():
with lock:
# only one thread can execute code there
有关更多详细信息,请参见 Python 3锁定对象和Python中的线程同步机制.
For more details see Python 3 Lock Objects and Thread Synchronization Mechanisms in Python.
这篇关于锁定Python中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!