See 8.10 Queue — A synchronized queue class (at the top)
Answer from Pavel Anossov on Stack OverflowThe Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads.
See 8.10 Queue — A synchronized queue class (at the top)
The Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads.
We need a python3 version:
import threading
import queue
q = queue.Queue()
def worker():
while True:
item = q.get()
print(f'Working on {item}')
print(f'Finished {item}')
q.task_done()
# Turn-on the worker thread.
threading.Thread(target=worker, daemon=True).start()
# Send thirty task requests to the worker.
for item in range(30):
q.put(item)
# Block until all tasks are done.
q.join()
print('All work completed')
reference: https://docs.python.org/3/library/queue.html#queue-objects
algorithms - How are queues made thread-safe in Python - Software Engineering Stack Exchange
Beginner Question on Queue and Multithreading
python - Is `queue.Queue` thread-safe, when accessed by several subprocesses using `concurrent.futures.ProcessPoolExecutor`? - Stack Overflow
It's it a bad idea to access a Queue from two threads? (c#)
Videos
I'm starting to dabble with Queue and Multithreading. Conceptually, I get when and where you would want to introduce these into your code. However, I just want to make sure I'm understanding the use case relationship between the two. Most online resources seem to treat the two as conjoined, but this seems to be under the assumption they will be used at larger scales.
My question, is Queue paired with Multithreading just so you can control the number of threads at any given moment without the program ending due to a lack of open threads? So, if I won't need more than 10 threads at a time then incorporating Queue might not be necessary. However, if I plan to have over 100 threads concurrently (assuming this is hitting some kind of processing limitation) then Queue should be incorporated?
Thanks!
ProcessPoolExecutor uses multiprocessing.queues.Queue for the call queue and a mp_context.SimpleQueue (multiprocessing) for the result queue - which are used to communicate between a local thread and the processes.
Nice graphic of ProcessPoolExecutor
- concurrent.futures.ProcessPoolExecutor stuff uses multiprocessing Queues to communicate between threads and processes.
- The multiprocessing.queues.Queue docs specifically state it is thread and process safe
- At the bottom of the queue documentation there is a note referring to the multiprocessing.Queue object
... for use in a multi-processing (rather than multi-threading) context
There is a Queue developed for this in the multiprocessing library
from multiprocessing import Queue
This uses sockets to send byte data which is thread-safe.