Dino Geek, try to help you

How to use queue module in Python?


The queue module in Python provides several classes for multi-producer, multi-consumer queues. It is especially useful in threaded programming.

Here’s a simple example on how you can use the Queue class:

```
import queue
import threading

def worker(q): while True: item = q.get() if item is None: break

print(f’Working on {item}’) q.task_done()

q = queue.Queue()

thread = threading.Thread(target=worker, args=(q,))
thread.start()

  1. put items in the queue …
    for item in range(5): print(f’Adding {item} to the queue’) q.put(item) # add item to the queue
  1. wait for all items to be processed …
    q.join()
  1. to stop the worker, add None to the queue
    q.put(None)
    thread.join()
    ```

In this example, we have a single worker thread that consumes some data from a queue. We put some numbers (0 to 4) into the queue and for each item we tell the worker to process it by calling `q.put(item)`.

Once all items have been processed we call `q.join()` to block until all items have been gotten and processed.

We can stop the worker by putting `None` in the queue and the worker breaks its loop when it retrieves `None`.

More informations:

- `queue.Queue(maxsize)`: Constructor for a FIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached.

- `Queue.qsize()`: Returns the approximate size of the queue.

- `Queue.empty()`: Return True if the queue is empty.

- `Queue.full()`: Return True if the queue is full.

- `Queue.put(item, block=True, timeout=None)`: Put item into the queue.

- `Queue.get(block=True, timeout=None)`: Remove and return an item from the queue.

- `Queue.task_done()`: Indicate that a formerly enqueued task is complete.

- `Queue.join()`: Blocks until all items in the queue have been gotten and processed.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use