Is there any way to block a critical area like with Java synchronized in Django?
You can use locks to make sure that only one Thread will access a certain block of code at a time.
To do this, you simply create a Lock
object then acquire the lock before the block of code you want to synchronize. All the threads must have access to the same Lock
object for this to work. An example:
from threading import Lock, Thread
lock = Lock()
def do_something():
lock.acquire() # will block if another thread has lock
try:
# ... use lock
finally:
lock.release()
Thread(target=do_something).start()
Thread(target=do_something).start()
For more information , see http://effbot.org/zone/thread-synchronization.htm.