Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Queue.get block main?

Tags:

python

I know that Queue.get() method in python is a blocking function. I need to know if I implemented this function inside the main, waiting for an object set by a thread, does this means that all the main will be blocked.

For instance, if the main contains functions for transmitter and receiver, will the two work together or not?

like image 202
user5376 Avatar asked Oct 06 '13 06:10

user5376


1 Answers

Yes -- if you call some_queue.get() within either the thread or the main function, the program will block there until some object as passed through the queue.


However, it is possible to use queues so that they don't block, or so that they have a timeout of some kind:

import Queue

while True:
    try:
        data = some_queue.get(False)  
        # If `False`, the program is not blocked. `Queue.Empty` is thrown if 
        # the queue is empty
    except Queue.Empty:
        data = None

    try:
        data2 = some_queue.get(True, 3)  
        # Waits for 3 seconds, otherwise throws `Queue.Empty`
    except Queue.Empty:
        data = None

You can do the same for some_queue.put -- either do some_queue.put(item, False) for non-blocking queues, or some_queue.put(item, True, 3) for timeouts. If your queue has a size limit, it will throw a Queue.Full exception if there is no more room left to append a new item.

like image 77
Michael0x2a Avatar answered Sep 26 '22 01:09

Michael0x2a