Thread Synchronization in Django

风格不统一 提交于 2019-12-06 03:10:57

问题


Is there any way to block a critical area like with Java synchronized in Django?


回答1:


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. An example:

lock = Lock()

lock.acquire()   # will block if another thread has lock
try:
    ... use lock
finally:
    lock.release() 

For more information , see http://effbot.org/zone/thread-synchronization.htm.




回答2:


My approach is to use the locking features of the database. This also works with multiple server processes.

I define a model as:

from django.db import models

class ThreadSafe(models.Model):
    key = m.CharField(max_length=80, unique=True)

And then a context manager function as:

from contextlib import contextmanager
from django.db.transaction import atomic

@contextmanager
def lock(key):
    pk = ThreadSafe.objects.get_or_create(key=key)[0].pk
    try:
        objs = ThreadSafe.objects.filter(pk=pk).select_for_update()
        with atomic():
            list(objs)
            yield None
    finally:
        pass

And then I have a thread/process safe lock by simply doing:

with lock("my_key"):
    do_scary_stuff_here()

This requires a database with support for transactions.




回答3:


Great article Justin, just one thing using python 2.5 makes this way easier

In Python 2.5 and later, you can also use the with statement. When used with a lock, this statement automatically acquires the lock before entering the block, and releases it when leaving the block:

from future import with_statement # 2.5 only

with lock: ... access shared resource



来源:https://stackoverflow.com/questions/2534943/thread-synchronization-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!