Is it possible to prioritise a lock?

断了今生、忘了曾经 提交于 2019-12-03 05:50:06

Make the Feeder's acquisition of the lock blocking, and the consumer's non-blocking.
So for the feeder:

try:
    with my_lock.acquire(): #locks block by default
        do stuff
finally:
    my_lock.release()

And the consumers:

while True:
   try:
      locked = my_lock.acquire(blocking=False)
      if locked:
         do stuff
   finally:
      if locked:
         my_lock.release()
   time.sleep(seconds=10)

Instead of trying to change the locking priority, try changing the process priority itself such that feeder has a higher priority than the consumer. The workaround you used basically simulates this but with less efficiency.

To change process priority,

On Unix: use os.setpriority()

Refer the docs

On windows, use a third party module psutil.

Refer to this thread and Psutil Docs.

ADR

It is not perfect, but it must work:

In "feeder":

feeder_lock_object.lock()
consumer_lock_object.lock()
try:
    ...
finally:
    feeder_lock_object.release()
    consumer_lock_object.release()

In "consumer":

while True:
    with consumer_lock_object:
        if feeder_lock_object.is_locked:
            continue
        ...

But I think it will be better when you will be use Queue.

If you use this method, be careful about how you implement the lock object. You should initialize the pool with an initializer function that creates these lock objects as global params. Refer to this.

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