Creating and waiting for threads by hand is tedious and error-prone. The concurrent.futures module offers a higher-level interface: a pool (a fixed group of workers) to which you send tasks.
ThreadPoolExecutor and map
ThreadPoolExecutor(max_workers=n) keeps n threads and distributes the tasks among them. pool.map(f, data) applies f to each item and returns the results in input order.
# Not run in the browser corrector (it cannot create real threads).
from concurrent.futures import ThreadPoolExecutor
import time
def square(n):
time.sleep(0.05) # simulates an I/O wait
return n * n
with ThreadPoolExecutor(max_workers=3) as pool:
results = list(pool.map(square, [1, 2, 3, 4, 5, 6]))
print(results) # [1, 4, 9, 16, 25, 36] (in the same input order)
Distributing jobs among a fixed number of workers, with its clock, is what you compute in Worker pool, and splitting the work into chunks that are combined afterwards (*map-reduce*) is Splitting work into chunks.
submit and futures
pool.submit(f, args) launches a task and returns a future (Future): a promise of a result that will arrive. f.result() waits for it and returns it (or re-raises the exception that happened in the task). as_completed hands out the futures as they finish.
# Not run in the browser corrector (it cannot create real threads).
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def task(name, pause):
time.sleep(pause)
return f"{name} done"
with ThreadPoolExecutor() as pool:
futures = [pool.submit(task, "slow", 0.1), pool.submit(task, "fast", 0.02)]
for f in as_completed(futures): # in the order they finish
print(f.result())
# fast done
# slow done
Processes: ProcessPoolExecutor
The same interface works for processes: ProcessPoolExecutor distributes the work among separate processes, which do use several cores and avoid the GIL. It is the option for CPU-bound tasks. Arguments and results travel between processes, so they must be serializable (*pickle*), and on some systems the main code must be under if __name__ == "__main__":.
queue.Queue: communicating between threads safely
Instead of sharing lists and protecting everything with locks, it is simpler for threads to pass messages through a queue. queue.Queue is thread-safe and keeps FIFO order (first in, first out). With maxsize you limit its capacity. put/get wait if there is no room or no data; put_nowait/get_nowait do not wait and raise queue.Full/queue.Empty. This queue also works in the corrector:
import queue
queue_ = queue.Queue(maxsize=2)
queue_.put("a")
queue_.put("b")
print(queue_.qsize(), queue_.full()) # 2 True
try:
queue_.put_nowait("c") # it does not fit
except queue.Full:
print("Queue full") # Queue full
print(queue_.get(), queue_.get()) # a b (FIFO: the oldest comes out)
try:
queue_.get_nowait() # it is empty
except queue.Empty:
print("Queue empty") # Queue empty
The producer-consumer pattern
A producer generates data and puts it in the queue; a consumer takes it out and processes it. The bounded queue stops the producer from overflowing memory if the consumer is slower. A special value (here None) tells the consumer there will be no more data.
# Not run in the browser corrector (it cannot create real threads).
import queue
import threading
queue_ = queue.Queue(maxsize=3)
END = None # end signal
def producer():
for i in range(1, 6):
queue_.put(i) # blocks if the queue is full
queue_.put(END)
def consumer():
while True:
item = queue_.get() # se bloquea si la queue_ it is empty
if item is END:
break
print("consumed", item)
threads = [threading.Thread(target=producer), threading.Thread(target=consumer)]
for h in threads:
h.start()
for h in threads:
h.join()
# consumed 1
# consumed 2
# consumed 3
# consumed 4
# consumed 5
You simulate this pattern, with its full-queue and empty-queue cases, in Producer and consumer.