Mutual Exclusion Thread Locking, With Dropping Of Queued Functions Upon Mutex/lock Release, In Python?
This is the problem I have: I'm using Python 2.7, and I have a code which runs in a thread, which has a critical region that only one thread should execute at the time. That code c
Solution 1:
Seems like you want a queue-like behaviour, so why not use Queue
?
import threading
from Queue import Queue
import time
# threads advertise to this queue when they're waiting
wait_queue = Queue()
# threads get their task from this queue
task_queue = Queue()
defdo_stuff():
print"%s doing stuff" % str(threading.current_thread())
time.sleep(5)
defqueue_thread(sleep_time):
# advertise current thread waiting
time.sleep(sleep_time)
wait_queue.put("waiting")
# wait for permission to pass
message = task_queue.get()
print"%s got task: %s" % (threading.current_thread(), message)
# unregister current thread waiting
wait_queue.get()
if message == "proceed":
do_stuff()
# kill size-1 threads waitingfor _ inrange(wait_queue.qsize() - 1):
task_queue.put("die")
# release last
task_queue.put("proceed")
if message == "die":
print"%s died without doing stuff" % threading.current_thread()
pass
t1 = threading.Thread(target=queue_thread, args=(1, ))
t2 = threading.Thread(target=queue_thread, args=(2, ))
t3 = threading.Thread(target=queue_thread, args=(3, ))
t4 = threading.Thread(target=queue_thread, args=(4, ))
# allow first thread to pass
task_queue.put("proceed")
t1.start()
t2.start()
t3.start()
t4.start()
thread-1 arrives first and "acquires" the section, other threads come later to wait at the queue (and advertise they're waiting). Then, when thread-1 leaves it gives permission to the last thread at the queue by telling all other thread to die, and the last thread to proceed.
You can have finer control using different messages, a typical one would be a thread-id in the wait_queue
(so you know who is waiting, and the order in which it arrived).
You can probably utilize non-blocking operations (queue.put(block=False)
and queue.get(block=False)
) in your favour when you're set on what you need.
Post a Comment for "Mutual Exclusion Thread Locking, With Dropping Of Queued Functions Upon Mutex/lock Release, In Python?"