简体   繁体   中英

How does the queue.get() work in this case in python

I was studying this example

http://eli.thegreenplace.net/2011/12/27/python-threads-communication-and-stopping/

He used like this

while not self.stoprequest.isSet():
    try:
        dirname = self.dir_q.get(True, 0.05)
        ... # do work
    except Queue.Empty:
        continue

I did n't get why he used block element in dir_q.get(True)

i want to know how the program behave if i use

self.dir_q.get()

Docs say that if we don't give anything then if there is soomething in queue , it will get it othwise it will raise exception.

i think whats problem with that

what the block , and timeout is doing

Read the documentation on the Queue.

Queue.get([block[, timeout]]) Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

When the 'block' argument (not 'element') is True, and the 'timeout' a positive number, the Queue will wait 'timeout' seconds until an element is available in the Queue. If the Queue was empty at the time Queue.get() was called, and no other thread Queue.put()'s an element onto the Queue within the specified 'timeout' (eg .05 secs), the Queue raises Empty. Otherwise it returns the first element that was Queue.put() by another thread.

self.dir_q.get() blocks until an item is available; therefore your program might not be able to react on self.stoprequest.set() in time if you remove the timeout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM