在Python中,如何保证读取和锁定之间的同步性?

2024-10-03 11:16:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了以下函数,它等待线程安全布尔值从1更改为0,然后再继续:

from multiprocessing import Value
from time import sleep

blJobInProcess = Value('i',0)

#Function for which multiple threads will spin up
def awaitAndExecuteJob():
  #Wait for Job to Free
  while blJobInProcess.value:
    sleep(5)

  #Lock Queue
  with blJobInProcess.get_lock():
    blJobInProcess.value = 1
  ...

  with blJobInProcess.get_lock():
     blJobInProcess.value = 0

我如何保证在进程释放锁,然后在while循环中读取后,它将打开锁并将值更改为1?如果在读取之后但在锁被激活之前,另一个线程读取blJobInProcess,然后尝试执行作业,而不是继续等待,该怎么办


Tags: 函数fromimportlockforgettimevalue