BerndGit
BerndGit

Reputation: 1660

Python threads: locking within while statement

I'm learning multithreading with Python. My task is a queueing System. This is my code:

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

The Problem is that the Queue might be modified after after checking it's length and applying the lock.

So I would need something like (which is obviously not valid code):

while lock.acquire(), len(Queue)>0:   # not working
   item =  Queue[0, :]
   Queue = np.delete(Queue,  0, 0)

   lock.release()

How to best solve this?

Upvotes: 2

Views: 1108

Answers (1)

Ioane Sharvadze
Ioane Sharvadze

Reputation: 2148

what about this?

    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

Upvotes: 1

Related Questions