【问题标题】:Python threads: locking within while statementPython线程:在while语句中锁定
【发布时间】:2015-04-05 11:16:22
【问题描述】:

我正在使用 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()

如何最好地解决这个问题?

【问题讨论】:

    标签: python multithreading thread-safety


    【解决方案1】:

    这个呢?

        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
    

    【讨论】:

    • 好点。通常我不使用break 语句。但在这里他们使用了显着的好处。谢谢
    猜你喜欢
    • 2018-11-29
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多