Python 个线程:在 while 语句中锁定
Python threads: locking within while statement
我正在使用 Python 学习多线程。我的任务是排队系统。这是我的代码:
lock = thread.allocate_lock()
while len(Queue)>0:
lock.acquire()
# get item from Queue
item = Queue[0, :]
Queue = np.delete(Queue, 0, 0)
lock.release()
# process item
# some code here
问题是在检查队列长度并应用锁后,队列可能会被修改。
所以我需要类似的东西(这显然不是有效代码):
while lock.acquire(), len(Queue)>0: # not working
item = Queue[0, :]
Queue = np.delete(Queue, 0, 0)
lock.release()
如何最好地解决这个问题?
这个呢?
lock = thread.allocate_lock()
while true:
lock.acquire()
if len(Queue) <= 0:
lock.release()
break
# get item from Queue
item = Queue[0, :]
Queue = np.delete(Queue, 0, 0)
lock.release()
# process item
# some code here
我正在使用 Python 学习多线程。我的任务是排队系统。这是我的代码:
lock = thread.allocate_lock()
while len(Queue)>0:
lock.acquire()
# get item from Queue
item = Queue[0, :]
Queue = np.delete(Queue, 0, 0)
lock.release()
# process item
# some code here
问题是在检查队列长度并应用锁后,队列可能会被修改。
所以我需要类似的东西(这显然不是有效代码):
while lock.acquire(), len(Queue)>0: # not working
item = Queue[0, :]
Queue = np.delete(Queue, 0, 0)
lock.release()
如何最好地解决这个问题?
这个呢?
lock = thread.allocate_lock()
while true:
lock.acquire()
if len(Queue) <= 0:
lock.release()
break
# get item from Queue
item = Queue[0, :]
Queue = np.delete(Queue, 0, 0)
lock.release()
# process item
# some code here