Locking a method in Python?
Asked Answered
B

1

26

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.

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.

Baal answered 25/8, 2016 at 12:49 Comment(0)
N
40

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

Or with context managment:

def foo():
    with lock:
        # only one thread can execute code there

For more details see Python 3 Lock Objects and Thread Synchronization Mechanisms in Python.

Nievesniflheim answered 25/8, 2016 at 14:2 Comment(1)
Locks support the context management protocol, you generally should be promoting that usage instead of explicit method calls.Classmate

© 2022 - 2025 — McMap. All rights reserved.