Free cookie consent management tool by TermsFeed get() method of Queue class | Pythontic.com

Get() method of Queue class

Method Name:

get

Method Signature:

get(item, block=True, timeout=None)

Parameters:

item – The item that is to be added to the queue.

block – Whether the function should block till an item is available for retrieval from the queue.

timeout – Number of seconds to wait till an item is available.

Return Value:

object

Overview:

  • The get() method removes an item from a queue and returns it.
  • The get() method can be executed either in blocking mode or non-blocking mode.
  • In blocking mode the method waits till an item is available, which is specified through the Boolean parameter block
  • If the timeout is specified, the method waits till an item is available till the elapse of timeout number seconds.

Example:

# Example Python program that uses Queue.get()

# in a producer/consumer scenario

import queue

import threading

import os

import time

 

try:

    # Function for reading messages from the queue

    def msgread(q):

        while(True):

            key = q.get();

            print("msgread:%s"%key);

            time.sleep(1);

 

    # Function for writing messages into the queue

    def msgwrite(q):

        while(True):

            key = os.urandom(16);

            q.put(key);

            print("msgwrite:%s"%key);

            time.sleep(1);

 

    # Create a synchronized queue

    syncQueue = queue.Queue(maxsize=5);

 

    # Create reader and writer threads

    rthread = threading.Thread(target=msgread, args=(syncQueue,));

    wthread = threading.Thread(target=msgwrite, args=(syncQueue,));

 

    # Start the reader and writer threads

    rthread.start();

    wthread.start();

 

    # Wait for the reader and writer threads to complete

    rthread.join();

    wthread.join();

 

except KeyboardInterrupt:   

    print('Keyboard interrupt received from user');

    try:

        sys.exit(0);

    except:

        os._exit(0);

 

Output:

msgwrite:b'\x1d\n@\xa9z\xad\x01\xe4\x1ct\x14\xfd\x1b\xc0\xe9w'

msgread:b'\x1d\n@\xa9z\xad\x01\xe4\x1ct\x14\xfd\x1b\xc0\xe9w'

msgwrite:b't\xcbY\xd4\x1eF\x81\xcevy\x06\xe6\\#\xf1!'

msgread:b't\xcbY\xd4\x1eF\x81\xcevy\x06\xe6\\#\xf1!'

msgwrite:b'\x90c,\xf9\\\x1c\xeb\xdfZ]\xa2\xbd\xf5h\x88\x14'

msgread:b'\x90c,\xf9\\\x1c\xeb\xdfZ]\xa2\xbd\xf5h\x88\x14'

msgwrite:b'\xe3-A\xba[\x10G:\x10o<\xa9)\xcdh\xe6'

msgread:b'\xe3-A\xba[\x10G:\x10o<\xa9)\xcdh\xe6'

msgwrite:b'`\xe9\xa9R\x80sB;\r%^2"\xa35Y'

msgread:b'`\xe9\xa9R\x80sB;\r%^2"\xa35Y'

^CKeyboard interrupt received from user


Copyright 2025 © pythontic.com