Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python queue Module

Python queue Module

In Python,queue The module provides a thread-safe queue implementation for safely passing data in multithreaded programming.

A queue is a first-in-first-out (FIFO) data structure;queue the module provides several queue types, including Queue、LifoQueue and PriorityQueue, to meet different needs.


Queue types

1. Queue

Queue Is queue The most commonly used queue type in the module; it implements a standard first-in-first-out (FIFO) queue. Here is Queue The basic usage of

Example

import

queue

Create a queue

q

=

queue.

Queue

(

)

Add an element to the queue

q.

put

(

1

)

q.

put

(

2

)

q.

put

(

3

)

Get an element from the queue

print

(

q.

get

(

)

)

 

Output: 1

print

(

q.

get

(

)

)

 

Output: 2

print

(

q.

get

(

)

)

 

Output: 3

2. LifoQueue

LifoQueue is a last-in-first-out (LIFO) queue, similar to a stack. Here is LifoQueue The basic usage of

Example

import

queue

Create a LIFO queue

q

=

queue.

LifoQueue

(

)

Add an element to the queue

q.

put

(

1

)

q.

put

(

2

)

q.

put

(

3

)

Get an element from the queue

print

(

q.

get

(

)

)

 

Output: 3

print

(

q.

get

(

)

)

 

Output: 2

print

(

q.

get

(

)

)

 

Output: 1

3. PriorityQueue

PriorityQueue is a priority queue whose elements are retrieved in priority order. Here is PriorityQueue The basic usage of

Example

import

queue

Create a priority queue

q

=

queue.

PriorityQueue

(

)

Add elements to the queue as tuples (priority, data)

q.

put

(

(

3

,

'Low priority'

)

)

q.

put

(

(

1

,

'High priority'

)

)

q.

put

(

(

2

,

'Medium priority'

)

)

Get an element from the queue

print

(

q.

get

(

)

)

 

Output: (1, 'High priority')

print

(

q.

get

(

)

)

 

Output: (2, 'Medium priority')

print

(

q.

get

(

)

)

 

Output: (3, 'Low priority')


// 2022-01-01 00:00:00 GMT

1. put(item, block=True, timeout=None)

data to the child component via item Put an item into the queue. If block is True and the queue is full, wait for timeout seconds until space becomes available. If timeout is None, wait indefinitely.

2. get(block=True, timeout=None)

Get and remove an item from the queue. If block is True and the queue is empty, wait for timeout seconds until an item is available. If timeout is None, wait indefinitely.

3. qsize()

Return the number of items in the queue.

4. empty()

If the queue is empty, return True; otherwise, returns False。

5. full()

If the queue is full, return True; otherwise, returns False。


Thread Safety

queue All queue types in the module are thread-safe, which means multiple threads can safely operate on the same queue at the same time without additional synchronization. This makes the queue module an ideal choice for passing data in multithreaded programming.


Example: a multithreaded queue

The following is an example of using Queue to pass data between multiple threads:

Example

import

queue

import

threading

import

time

Create a queue

q

=

queue.

Queue

(

)

Producer thread

def

producer

(

)

:

   

for

i

in

range

(

5

)

:

       

print

(

f

'Produce {i}'

)

        q.

put

(

i

)

       

time

.

sleep

(

1

)

Consumer thread

def

consumer

(

)

:

   

while

True

:

        item

=

q.

get

(

)

       

if

item

is

None

:

           

break

       

print

(

f

'Consume {item}'

)

        q.

task_done

(

)

Start the producer thread

producer_thread

=

threading

.

Thread

(

target

=

producer

)

producer_thread.

start

(

)

Start the consumer thread

consumer_thread

=

threading

.

Thread

(

target

=

consumer

)

consumer_thread.

start

(

)

Wait for the producer thread to finish

producer_thread.

join

(

)

Wait until all tasks in the queue are done

q.

join

(

)

Send a termination signal

q.

put

(

None

)

consumer_thread.

join

(

)


Common attributes and methods

The following table lists the common classes, methods and attributes of Python's queue module (thread-safe queues), with descriptions and examples:

Core classes of the queue module

class Description Applicable scenarios
queue.Queue First-in-first-out (FIFO) queue General task queue
queue.LifoQueue Last-in-first-out (LIFO) queue (similar to a stack) Scenarios that require last-in-first-out
queue.PriorityQueue Priority queue (implemented with a min-heap) Process tasks by priority
queue.SimpleQueue A simpler FIFO queue (Python 3.7+) Scenarios that do not need advanced features

Common methods (supported by all queue classes)

Method Description Example Return Value
put(item) Put an item q.put("task1") None
get() Get and remove an item item = q.get() Queue items
empty() Check whether the queue is empty if q.empty(): True/False
full() Check whether the queue is full if q.full(): True/False
qsize() Return the current size of the queue size = q.qsize() Integers
task_done() Mark a task as done (used withjoin()) q.task_done() None
join() Block until all tasks are done q.join() None

Blocking control parameters

Parameters Description Default value Example
block Whether to block when the queue is empty / full True q.get(block=False)
timeout Blocking timeout in seconds None q.put(x, timeout=5)

PriorityQueue-specific usage

Element format:(priority, data); smaller priority values are dequeued first

Example

pq

=

queue.

PriorityQueue

(

)

pq.

put

(

(

1

,

"low"

)

)

pq.

put

(

(

0

,

"high"

)

)

print

(

pq.

get

(

)

[

1

]

)

 

Output: "high"

Example

Producer-consumer model:

Example

import

queue

,

threading

q

=

queue.

Queue

(

maxsize

=

3

)

 

A queue with capacity 3

def

producer

(

)

:

   

for

i

in

range

(

5

)

:

        q.

put

(

f

"Task-{i}"

)

       

print

(

f

"Produced: Task-{i}"

)

def

consumer

(

)

:

   

while

True

:

        item

=

q.

get

(

)

       

print

(

f

"Consumed: {item}"

)

        q.

task_done

(

)

threading

.

Thread

(

target

=

producer

,

daemon

=

True

)

.

start

(

)

threading

.

Thread

(

target

=

consumer

,

daemon

=

True

)

.

start

(

)

q.

join

(

)

 

Wait for all tasks to finish

Priority task processing:

Example

pq

=

queue.

PriorityQueue

(

)

pq.

put

(

(

3

,

"Scan"

)

)

pq.

put

(

(

1

,

"Emergency"

)

)

pq.

put

(

(

2

,

"Log"

)

)

while

not

pq.

empty

(

)

:

   

print

(

pq.

get

(

)

[

1

]

)

 

Output order: Emergency -> Log -> Scan

Non-blocking get (avoids deadlocks):

Example

try

:

    item

=

q.

get_nowait

(

)

 

Equivalent to q.get(block=False)

except

queue.

Empty

:

   

print

(

"Queue is empty"

)