Free cookie consent management tool by TermsFeed The put() method of Queue class in Python | Pythontic.com

The put() method of Queue class in Python

Method Name:

put

Method Signature:

put()

Parameters:

block - Specify whether put() should block for an item to be removed from the queue.

timeout- Number of seconds to wait for an item to be inserted into the queue while the queue is in its maximum capacity.

Return Value:

None

Overview:

  • The method put() adds an element to the queue represented by a Queue instance.
  • The method put() will block if the queue has reached its maximum capacity or executed in blocking mode.

Example:

  • The example creates a reader thread and a writer thread.
  • The writer thread adds an element to the shared queue while the writer thread removes an element from a queue.
  • The program exits on a keyboard interrupt (control-c).

# Example Python program that uses put() method

# to add elements to a queue.Queue instance

import queue

import threading

import os

import sys

import random

import time

 

try:

    # Function for writer thread

    def writer(sq):

        while(True):

            data = random.randint(0, 9999);

            time.sleep(1);

            sq.put(data);

            print("writer:added %d"%data);

 

    # Function for reader thread

    def reader(sq):

        while(True):

            data = sq.get();

            time.sleep(1);

            print("reader:removed %d"%data);

 

    # Create a synchronized queue instance

    sharedQueue = queue.Queue();

 

    # Create reader and writer threads

    threads     = [None, None];

    threads[0]  = threading.Thread(target=reader, args=(sharedQueue,));

    threads[1]  = threading.Thread(target=writer, args=(sharedQueue,));

 

    # Start the reader and writer threads

    for thread in threads:

        thread.start();

 

    # Wait for the reader and writer threads to exit

    for thread in threads:

        thread.join();

 

except KeyboardInterrupt:   

    print('Keyboard interrupt received from user');

    try:

        sys.exit(0);

    except:

        os._exit(0);

 

Output:

writer:added 5358

writer:added 1746

reader:removed 5358

writer:added 9845

reader:removed 1746

writer:added 1414

reader:removed 9845

writer:added 6417

reader:removed 1414

writer:added 9475

reader:removed 6417

writer:added 1947

reader:removed 9475

^CKeyboard interrupt received from user

 


Copyright 2025 © pythontic.com