Bitpath

Lesson 2 · Unit 03

Worker pools

A fixed crew of workers and a queue of tasks

13 exercisesabout 3 min

What you practise

  • Thread pools and process pools, futures, map over inputs, choosing the pool size for I/O vs CPU work, why a thread per task doesn't scale

Try a question from this lesson

Pick one

A scraper starts one new thread for each of 100,000 URLs, all at the same moment. What is the most likely result?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

A pool

A pool is a fixed crew of workers fed from a queue of tasks: producer and consumer, ready-made.

ThreadPoolExecutor(2) makes two worker threads. pool.map(f, items) runs f on every item and returns the results in the order of the items.

Leaving the with block waits for all the work to finish.

Python
import concurrent.futures as cf

def square(n):
    return n * n

with cf.ThreadPoolExecutor(2) as pool:
    res = pool.map(square, [3, 1, 2])
    print(list(res))

Concept

How many workers

Size the pool by what the tasks spend their time on.

I/O-bound tasks mostly wait, so one core can serve many of them: tens or hundreds of threads are fine, up to what the other end will tolerate.

CPU-bound tasks keep a core busy: use about one worker per core. More workers than cores only adds switching.

10 more exercises in the app

  • 4× type the answer
  • 2× true or false
  • 2× multiple choice
  • 1× fill the blanks
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy