Programming Search⌘K

Taskcore

Run tasks on a thread pool

Also called thread pool example, worker pool, ExecutorService example, newFixedThreadPool, ThreadPoolExecutor example, Go worker pool, submit tasks to a pool, Parallel.For MaxDegreeOfParallelism.

Submit one job for each number to a pool of at most a given number of worker threads, wait until every job has finished, and return the results in the order of the numbers.

Task

Write a function steps_on_pool(workers, numbers) that runs one job for each number on a pool of worker threads. A job counts the steps that take its number to 1, where a step halves an even number and changes an odd number n to 3n + 1. The pool has at most workers threads, so at most workers jobs run at the same time. The function waits until every job has finished, stops the pool, and returns the counts in the order of the numbers. For example, steps_on_pool(2, [1, 2, 3, 6]) is [0, 1, 7, 8].

workers is 1 to 8. There are 0 to 1,000 numbers, and each number is 1 to 1,000,000. A count fits in 32 bits, but the numbers on the way to 1 can be larger than 2^31, so a job needs 64-bit arithmetic. The task is about the pool: a fixed set of threads takes jobs from a queue, many more jobs than threads go through it, and the results come back in the order of the input. Wait for threads to finish starts one thread for each job instead.

Solutions

Language Pool Submit Results Stop
Python ThreadPoolExecutor(max_workers=workers) submit Future.result() the end of the with block
JavaScript an array of workers Node.js workers postMessage to a free worker a message from the worker terminate() on each worker
TypeScript as JavaScript as JavaScript as JavaScript as JavaScript
Java Executors.newFixedThreadPool(workers) submit Future.get() close() at the end of try
C# the .NET thread pool, with MaxDegreeOfParallelism Parallel.For an array slot for each job Parallel.For returns
Go workers goroutines that read one channel a send on the channel a slice element for each job close the channel, then WaitGroup.Wait
Rust workers scoped threads that share one mpsc receiver send on the channel a second channel with (index, count) pairs the end of thread::scope
C workers threads from pthread_create an index behind a mutex an array slot for each job pthread_join on each thread
C++ a small ThreadPool class with std::jthread submit returns a std::future std::future::get() the destructor of the pool
  • Python uses ThreadPoolExecutor, "An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously".1 submit returns a Future at once. Leaving the with block waits for all jobs, and result() gives the value of each one.1
  • Java uses Executors.newFixedThreadPool, which "reuses a fixed number of threads operating off a shared unbounded queue". A job that comes when all threads are busy waits "in the queue until a thread is available".2 ExecutorService has a close() method, which "waits until all tasks have completed execution and the executor has terminated", so a try block stops the pool.3
  • C# does not make its own threads. The .NET thread pool gives "a pool of worker threads that are managed by the system".4 Parallel.For runs the jobs on it, and MaxDegreeOfParallelism "limits the number of concurrent operations to the set value".5 Parallel.For returns "when all threads have completed".6
  • Go follows Go by Example: the workers "receive work on the jobs channel and send the corresponding results".7 Here each worker writes the result to its own element of a slice, so the solution needs no results channel. Closing the jobs channel ends the range loop in each worker, and a WaitGroup waits for them.
  • Rust follows the thread pool of the Rust book: the workers share one receiver of an mpsc channel behind a Mutex.8 The workers run in thread::scope, so that they can borrow numbers. When the sender is dropped, the channel has "hung up", and recv returns an error once the queue is empty.9 Then the worker stops.
  • C keeps the queue as an index into the array, behind a pthread_mutex_t. A worker locks the mutex, takes the next index, and unlocks it before it runs the job. If another worker holds the mutex, the call "shall block until the mutex becomes available".10
  • C++ has no thread pool in the standard library, so the solution has a small one: a queue of std::packaged_task, a mutex, a condition variable and a vector of std::jthread. A packaged_task stores the return value "or exception thrown" in a shared state that a std::future reads.11 The destructor lets the threads finish the queue and joins them.
  • JavaScript and TypeScript have no pool of workers in Node.js, but the Node.js documentation advises "use a pool of Workers" when there are many jobs, because otherwise "the overhead of creating Workers would likely exceed their benefit".12 The solution starts workers workers and gives each one a new job when it sends back a result.

Alternatives

  • A process pool in Python. In CPython, "only one thread can execute Python code at once", so a thread pool does not make CPU-bound Python code faster.13 ProcessPoolExecutor has the same interface and can "side-step the Global Interpreter Lock", but only with picklable jobs and results.1
  • invokeAll in Java. It takes a collection of Callable jobs and returns "a list of Futures holding their status and results when all complete".3
  • Data parallelism in Rust. The rayon crate has par_iter, which "provides parallel implementations of many iterative functions" such as map, and a global thread pool that ThreadPoolBuilder can customize.14 With rayon, the solution is numbers.par_iter().map(...).collect().
  • A configurable pool in Java. ThreadPoolExecutor takes a core size, a maximum size and a queue. With a bounded queue, a job that cannot be queued and cannot get a new thread "will be rejected".15

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: no numbers give an empty list. The pool can start and stop with no jobs.
  • one-worker: with one worker, the jobs run one after another, but still not on the caller's thread.
  • more-workers-than-jobs: 8 workers and 2 jobs. Some workers get no job, and the pool must still stop. The JavaScript solution starts only as many workers as there are jobs.
  • duplicates: equal numbers are separate jobs with separate results.
  • wide-intermediate: the sequence from 113,383 reaches 2,482,111,348, and the sequence from 837,799 reaches 2,974,984,576. Both are larger than 2^31 − 1, so 32-bit arithmetic overflows. JavaScript numbers hold these values exactly.
  • many: 200 jobs on 4 workers. The jobs finish in an order that changes from run to run, and the results must still come back in the order of the numbers.

Pitfalls

  • A job that waits for another job of the same pool. If all threads of a pool run jobs that wait for jobs that are still in the queue, no thread is free to run those, and the pool deadlocks. The Python documentation shows a job that submits a second job to a pool of one worker and waits for it. The second job never runs, because "there is only one worker thread", and that thread runs the first job.1 Do not wait on a future of the same pool inside a job, or use a pool that is large enough.
  • Holding the lock while the job runs. In Rust, while let Ok(job) = receiver.lock().unwrap().recv() holds the lock until the end of the loop body. The Rust book explains that while let "does not drop temporary values until the end of the associated block", so other workers "cannot receive jobs".8 A let statement drops the guard at its end, as in the solution. The same rule holds in C: unlock the mutex before the job runs.
  • An unbounded queue. The queue of newFixedThreadPool has no limit.2 If jobs come faster than the workers finish them, the queue grows without limit. Use a ThreadPoolExecutor with a bounded queue, or limit the producer.15
  • A pool that is never stopped. The threads of a fixed pool "will exist until it is explicitly shutdown".2 Python joins the threads of a ThreadPoolExecutor before the interpreter exits.1 In both cases, a pool that is never shut down can keep the program alive or hold its threads after the work is done. Close the pool when its work is finished.
  • Results in the wrong order. Jobs on a pool finish in any order. Store each result at the index of its job, or keep the futures in the order of the input, as the solutions do.

Code

The build runs the native tests of each language in a pinned toolchain.

pool.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

"""Submit one job for each number to a fixed pool of worker threads and collect the results in order."""

from concurrent.futures import ThreadPoolExecutor


def collatz_steps(n: int) -> int:
    steps = 0
    while n != 1:
        n = n // 2 if n % 2 == 0 else 3 * n + 1
        steps += 1
    return steps


def steps_on_pool(workers: int, numbers: list[int]) -> list[int]:
    # The pool starts at most `workers` threads and gives each queued job to a free thread.
    # Leaving the with block waits for all jobs and stops the threads.
    with ThreadPoolExecutor(max_workers=workers) as pool:
        futures = [pool.submit(collatz_steps, n) for n in numbers]
    # Every future is done here; result() returns the value, or raises the exception of the job.
    return [future.result() for future in futures]
test_pool.py 36 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

import threading

import pytest

from pool import collatz_steps, steps_on_pool


def sequential(numbers):
    return [collatz_steps(n) for n in numbers]


CASES = {
    "four-jobs": (2, [1, 2, 3, 6], [0, 1, 7, 8]),
    "long-runs": (3, [27, 97, 871], [111, 118, 178]),
    "empty": (2, [], []),
    "one-worker": (1, [7, 8, 9], [16, 3, 19]),
    "more-workers-than-jobs": (8, [5, 6], [5, 8]),
    "duplicates": (3, [27, 27, 27, 1], [111, 111, 111, 0]),
    "wide-intermediate": (2, [113383, 837799], [247, 524]),
    "many": (4, list(range(1, 201)), sequential(range(1, 201))),
}


@pytest.mark.parametrize("name", CASES)
def test_steps_on_pool(name):
    workers, numbers, want = CASES[name]
    assert steps_on_pool(workers, numbers) == want


def test_pool_threads_have_stopped():
    before = threading.active_count()
    steps_on_pool(4, list(range(1, 101)))
    assert threading.active_count() == before
pool.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

#include "pool.hpp"

#include <condition_variable>
#include <deque>
#include <functional>
#include <future>
#include <mutex>
#include <thread>

namespace pool {

namespace {

// A fixed set of threads that take jobs from one queue.
class ThreadPool {
public:
    explicit ThreadPool(std::size_t workers) {
        try {
            for (std::size_t i = 0; i < workers; i++) {
                threads_.emplace_back([this] { run(); });
            }
        } catch (...) {
            stop();  // the threads that did start must not wait forever
            throw;
        }
    }

    // Lets the threads finish the queued jobs, then joins them.
    ~ThreadPool() {
        stop();
        // threads_ is the last member, so it is destroyed first: each std::jthread joins.
    }

    ThreadPool(const ThreadPool&) = delete;
    ThreadPool& operator=(const ThreadPool&) = delete;

    // Queues a job and returns a future for its result.
    std::future<std::int32_t> submit(std::function<std::int32_t()> job) {
        std::packaged_task<std::int32_t()> task(std::move(job));
        std::future<std::int32_t> result = task.get_future();
        {
            std::lock_guard lock(mutex_);
            queue_.push_back(std::move(task));
        }
        ready_.notify_one();
        return result;
    }

private:
    void stop() {
        {
            std::lock_guard lock(mutex_);
            stopping_ = true;
        }
        ready_.notify_all();
    }

    void run() {
        for (;;) {
            std::packaged_task<std::int32_t()> task;
            {
                std::unique_lock lock(mutex_);
                ready_.wait(lock, [this] { return stopping_ || !queue_.empty(); });
                if (queue_.empty()) {
                    return;  // stopping, and no job is left
                }
                task = std::move(queue_.front());
                queue_.pop_front();
            }
            task();  // runs without the lock; stores the value or the exception in the future
        }
    }

    std::mutex mutex_;
    std::condition_variable ready_;
    std::deque<std::packaged_task<std::int32_t()>> queue_;
    bool stopping_ = false;
    std::vector<std::jthread> threads_;
};

}  // namespace

std::int32_t collatz_steps(std::int64_t n) {
    std::int32_t steps = 0;
    while (n != 1) {
        n = n % 2 == 0 ? n / 2 : 3 * n + 1;
        steps++;
    }
    return steps;
}

std::vector<std::int32_t> steps_on_pool(std::size_t workers, const std::vector<std::int32_t>& numbers) {
    std::vector<std::future<std::int32_t>> futures;
    {
        ThreadPool threads(workers);
        for (std::int32_t n : numbers) {
            futures.push_back(threads.submit([n] { return collatz_steps(n); }));
        }
    }  // the destructor waits for every job and joins the threads
    std::vector<std::int32_t> results;
    for (auto& future : futures) {
        results.push_back(future.get());  // returns the value, or throws the exception of the job
    }
    return results;
}

}  // namespace pool
pool.hpp 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

#pragma once

#include <cstddef>
#include <cstdint>
#include <vector>

namespace pool {

// Returns the number of steps that take n to 1.
std::int32_t collatz_steps(std::int64_t n);

// Submits one job for each number to a pool of `workers` threads and returns the step counts in order.
// Throws std::system_error if a thread cannot be started.
std::vector<std::int32_t> steps_on_pool(std::size_t workers, const std::vector<std::int32_t>& numbers);

}  // namespace pool
test_pool.cpp 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

#include "pool.hpp"

#include <cstdint>
#include <iostream>
#include <string_view>
#include <vector>

static int failures = 0;

static void check(std::string_view name, std::size_t workers, const std::vector<std::int32_t>& numbers,
                  const std::vector<std::int32_t>& want) {
    if (pool::steps_on_pool(workers, numbers) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("four-jobs", 2, {1, 2, 3, 6}, {0, 1, 7, 8});
    check("long-runs", 3, {27, 97, 871}, {111, 118, 178});
    check("empty", 2, {}, {});
    check("one-worker", 1, {7, 8, 9}, {16, 3, 19});
    check("more-workers-than-jobs", 8, {5, 6}, {5, 8});
    check("duplicates", 3, {27, 27, 27, 1}, {111, 111, 111, 0});
    check("wide-intermediate", 2, {113383, 837799}, {247, 524});
    std::vector<std::int32_t> many, want;
    for (std::int32_t n = 1; n <= 200; n++) {
        many.push_back(n);
        want.push_back(pool::collatz_steps(n));
    }
    check("many", 4, many, want);
    if (failures == 0) {
        std::cout << "all tests passed\n";
    }
    return failures == 0 ? 0 : 1;
}
Pool.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

// Submit one job for each number to a fixed pool of worker threads and collect the results in order.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public final class Pool {
  private Pool() {}

  static int collatzSteps(long n) {
    int steps = 0;
    while (n != 1) {
      n = n % 2 == 0 ? n / 2 : 3 * n + 1;
      steps++;
    }
    return steps;
  }

  /** Returns the step count of each number, in the order of numbers. */
  public static int[] stepsOnPool(int workers, int[] numbers)
      throws InterruptedException, ExecutionException {
    List<Future<Integer>> futures = new ArrayList<>();
    // The pool has at most `workers` threads; jobs wait in its queue for a free thread.
    // close() waits until every submitted job has finished, and the threads then end.
    try (ExecutorService pool = Executors.newFixedThreadPool(workers)) {
      for (int n : numbers) {
        futures.add(pool.submit(() -> collatzSteps(n)));
      }
    }
    int[] results = new int[numbers.length];
    for (int i = 0; i < results.length; i++) {
      // get() returns the value, or throws ExecutionException with the exception of the job.
      results[i] = futures.get(i).get();
    }
    return results;
  }
}
PoolTest.java 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.concurrent.ExecutionException;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class PoolTest {
  static Stream<Arguments> cases() {
    int[] many = IntStream.rangeClosed(1, 200).toArray();
    int[] manyWant = IntStream.rangeClosed(1, 200).map(n -> Pool.collatzSteps(n)).toArray();
    return Stream.of(
        Arguments.of("four-jobs", 2, new int[] {1, 2, 3, 6}, new int[] {0, 1, 7, 8}),
        Arguments.of("long-runs", 3, new int[] {27, 97, 871}, new int[] {111, 118, 178}),
        Arguments.of("empty", 2, new int[] {}, new int[] {}),
        Arguments.of("one-worker", 1, new int[] {7, 8, 9}, new int[] {16, 3, 19}),
        Arguments.of("more-workers-than-jobs", 8, new int[] {5, 6}, new int[] {5, 8}),
        Arguments.of("duplicates", 3, new int[] {27, 27, 27, 1}, new int[] {111, 111, 111, 0}),
        Arguments.of("wide-intermediate", 2, new int[] {113383, 837799}, new int[] {247, 524}),
        Arguments.of("many", 4, many, manyWant));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void stepsOnPool(String name, int workers, int[] numbers, int[] want)
      throws InterruptedException, ExecutionException {
    assertArrayEquals(want, Pool.stepsOnPool(workers, numbers), name);
  }
}
pool.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

#include "pool.h"

#include <pthread.h>

// The shared state of the pool. The queue is the range of indexes from next to n.
struct pool {
    const int32_t *numbers;
    int32_t *out;
    size_t n;
    size_t next;  // guarded by lock
    pthread_mutex_t lock;
};

static int32_t collatz_steps(int64_t n) {
    int32_t steps = 0;
    while (n != 1) {
        n = n % 2 == 0 ? n / 2 : 3 * n + 1;
        steps++;
    }
    return steps;
}

static void *worker(void *arg) {
    struct pool *p = arg;
    for (;;) {
        // Take the next job under the lock, then run it without the lock.
        pthread_mutex_lock(&p->lock);
        size_t i = p->next;
        if (i < p->n) {
            p->next++;
        }
        pthread_mutex_unlock(&p->lock);
        if (i >= p->n) {
            return NULL;
        }
        p->out[i] = collatz_steps(p->numbers[i]);  // each job writes its own element
    }
}

bool steps_on_pool(size_t workers, const int32_t numbers[], size_t n, int32_t out[]) {
    if (workers == 0 || workers > POOL_MAX_WORKERS) {
        return false;
    }
    struct pool p = {.numbers = numbers, .out = out, .n = n, .next = 0};
    if (pthread_mutex_init(&p.lock, NULL) != 0) {
        return false;
    }
    pthread_t threads[POOL_MAX_WORKERS];
    size_t started = 0;
    while (started < workers && pthread_create(&threads[started], NULL, worker, &p) == 0) {
        started++;
    }
    // The threads that did start take all the jobs between them.
    for (size_t i = 0; i < started; i++) {
        pthread_join(threads[i], NULL);
    }
    pthread_mutex_destroy(&p.lock);
    return started > 0;
}
pool.h 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

#ifndef POOL_H
#define POOL_H

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

#define POOL_MAX_WORKERS 8

// Runs one job for each of the n numbers on a pool of 1 to POOL_MAX_WORKERS threads and writes
// the step count of numbers[i] to out[i]. Returns false if workers is out of range or no thread starts.
bool steps_on_pool(size_t workers, const int32_t numbers[], size_t n, int32_t out[]);

#endif
test_pool.c 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

#include "pool.h"

#include <stdio.h>

static int failures = 0;

static int32_t reference_steps(int64_t n) {
    int32_t steps = 0;
    while (n != 1) {
        n = n % 2 == 0 ? n / 2 : 3 * n + 1;
        steps++;
    }
    return steps;
}

static void check(const char *name, size_t workers, const int32_t numbers[], size_t n, const int32_t want[]) {
    int32_t got[200] = {0};
    if (!steps_on_pool(workers, numbers, n, got)) {
        fprintf(stderr, "case %s failed: the pool did not start\n", name);
        failures++;
        return;
    }
    for (size_t i = 0; i < n; i++) {
        if (got[i] != want[i]) {
            fprintf(stderr, "case %s failed at %zu: got %d, want %d\n", name, i, got[i], want[i]);
            failures++;
            return;
        }
    }
}

int main(void) {
    check("four-jobs", 2, (int32_t[]){1, 2, 3, 6}, 4, (int32_t[]){0, 1, 7, 8});
    check("long-runs", 3, (int32_t[]){27, 97, 871}, 3, (int32_t[]){111, 118, 178});
    check("empty", 2, NULL, 0, NULL);
    check("one-worker", 1, (int32_t[]){7, 8, 9}, 3, (int32_t[]){16, 3, 19});
    check("more-workers-than-jobs", 8, (int32_t[]){5, 6}, 2, (int32_t[]){5, 8});
    check("duplicates", 3, (int32_t[]){27, 27, 27, 1}, 4, (int32_t[]){111, 111, 111, 0});
    check("wide-intermediate", 2, (int32_t[]){113383, 837799}, 2, (int32_t[]){247, 524});
    int32_t many[200], want[200];
    for (int i = 0; i < 200; i++) {
        many[i] = i + 1;
        want[i] = reference_steps(i + 1);
    }
    check("many", 4, many, 200, want);
    if (steps_on_pool(0, many, 200, want) || steps_on_pool(POOL_MAX_WORKERS + 1, many, 200, want)) {
        fprintf(stderr, "case bad-workers failed: want false\n");
        failures++;
    }
    if (failures == 0) {
        printf("all tests passed\n");
    }
    return failures == 0 ? 0 : 1;
}
Pool.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

// Run one job for each number on the .NET thread pool, at most `workers` at a time,
// and collect the results in order.

using System.Threading.Tasks;

public static class Pool
{
    public static int CollatzSteps(long n)
    {
        int steps = 0;
        while (n != 1)
        {
            n = n % 2 == 0 ? n / 2 : 3 * n + 1;
            steps++;
        }
        return steps;
    }

    public static int[] StepsOnPool(int workers, int[] numbers)
    {
        var results = new int[numbers.Length];
        var options = new ParallelOptions { MaxDegreeOfParallelism = workers };
        // Parallel.For returns when every iteration has finished. Each iteration writes its own slot.
        Parallel.For(0, numbers.Length, options, i => results[i] = CollatzSteps(numbers[i]));
        return results;
    }
}
PoolTests.cs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

using System.Linq;
using Xunit;

public sealed class PoolTests
{
    public static TheoryData<string, int, int[], int[]> Cases => new()
    {
        { "four-jobs", 2, new[] { 1, 2, 3, 6 }, new[] { 0, 1, 7, 8 } },
        { "long-runs", 3, new[] { 27, 97, 871 }, new[] { 111, 118, 178 } },
        { "empty", 2, new int[] { }, new int[] { } },
        { "one-worker", 1, new[] { 7, 8, 9 }, new[] { 16, 3, 19 } },
        { "more-workers-than-jobs", 8, new[] { 5, 6 }, new[] { 5, 8 } },
        { "duplicates", 3, new[] { 27, 27, 27, 1 }, new[] { 111, 111, 111, 0 } },
        { "wide-intermediate", 2, new[] { 113383, 837799 }, new[] { 247, 524 } },
        { "many", 4, Enumerable.Range(1, 200).ToArray(),
          Enumerable.Range(1, 200).Select(n => Pool.CollatzSteps(n)).ToArray() },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void StepsOnPool(string name, int workers, int[] numbers, int[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Pool.StepsOnPool(workers, numbers));
    }
}
pool.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

// Submit one job for each number to a fixed pool of worker threads and collect the results in order.

import { Worker } from "node:worker_threads";

// Each worker waits for jobs, runs them one at a time and sends back each result.
const source = `
const { parentPort } = require("node:worker_threads");
parentPort.on("message", ({ index, n }) => {
  let steps = 0;
  while (n !== 1) {
    n = n % 2 === 0 ? n / 2 : 3 * n + 1;
    steps++;
  }
  parentPort.postMessage({ index, steps });
});
`;

// Returns a promise of the step counts, in the order of numbers.
export async function stepsOnPool(workers, numbers) {
  const results = new Array(numbers.length).fill(0);
  const size = Math.min(workers, numbers.length);
  const pool = Array.from({ length: size }, () => new Worker(source, { eval: true }));
  let next = 0;
  try {
    await Promise.all(
      pool.map(
        (worker) =>
          new Promise((resolve, reject) => {
            // Give the worker the next job, or finish when no job is left.
            const giveNext = () => {
              if (next === numbers.length) {
                resolve();
                return;
              }
              const index = next++;
              worker.postMessage({ index, n: numbers[index] });
            };
            worker.on("message", ({ index, steps }) => {
              results[index] = steps;
              giveNext();
            });
            worker.once("error", reject);
            giveNext();
          }),
      ),
    );
  } finally {
    // A worker with a message listener keeps running, so stop every worker.
    await Promise.all(pool.map((worker) => worker.terminate()));
  }
  return results;
}
pool.test.js 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { stepsOnPool } from "./pool.js";

function steps(n) {
  let count = 0;
  while (n !== 1) {
    n = n % 2 === 0 ? n / 2 : 3 * n + 1;
    count++;
  }
  return count;
}

const many = Array.from({ length: 200 }, (_, i) => i + 1);

const cases = [
  ["four-jobs", 2, [1, 2, 3, 6], [0, 1, 7, 8]],
  ["long-runs", 3, [27, 97, 871], [111, 118, 178]],
  ["empty", 2, [], []],
  ["one-worker", 1, [7, 8, 9], [16, 3, 19]],
  ["more-workers-than-jobs", 8, [5, 6], [5, 8]],
  ["duplicates", 3, [27, 27, 27, 1], [111, 111, 111, 0]],
  ["wide-intermediate", 2, [113383, 837799], [247, 524]],
  ["many", 4, many, many.map(steps)],
];

for (const [name, workers, numbers, want] of cases) {
  test(name, async () => {
    assert.deepEqual(await stepsOnPool(workers, numbers), want);
  });
}
pool.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

// Submit one job for each number to a fixed pool of worker threads and collect the results in order.

import { Worker } from "node:worker_threads";

// Each worker waits for jobs, runs them one at a time and sends back each result.
const source = `
const { parentPort } = require("node:worker_threads");
parentPort.on("message", ({ index, n }) => {
  let steps = 0;
  while (n !== 1) {
    n = n % 2 === 0 ? n / 2 : 3 * n + 1;
    steps++;
  }
  parentPort.postMessage({ index, steps });
});
`;

// Returns a promise of the step counts, in the order of numbers.
export async function stepsOnPool(workers: number, numbers: readonly number[]): Promise<number[]> {
  const results: number[] = new Array<number>(numbers.length).fill(0);
  const size = Math.min(workers, numbers.length);
  const pool = Array.from({ length: size }, () => new Worker(source, { eval: true }));
  let next = 0;
  try {
    await Promise.all(
      pool.map(
        (worker) =>
          new Promise<void>((resolve, reject) => {
            // Give the worker the next job, or finish when no job is left.
            const giveNext = () => {
              if (next === numbers.length) {
                resolve();
                return;
              }
              const index = next++;
              worker.postMessage({ index, n: numbers[index] });
            };
            worker.on("message", ({ index, steps }: { index: number; steps: number }) => {
              results[index] = steps;
              giveNext();
            });
            worker.once("error", reject);
            giveNext();
          }),
      ),
    );
  } finally {
    // A worker with a message listener keeps running, so stop every worker.
    await Promise.all(pool.map((worker) => worker.terminate()));
  }
  return results;
}
pool.test.ts 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { stepsOnPool } from "./pool.ts";

function steps(n: number): number {
  let count = 0;
  while (n !== 1) {
    n = n % 2 === 0 ? n / 2 : 3 * n + 1;
    count++;
  }
  return count;
}

const many = Array.from({ length: 200 }, (_, i) => i + 1);

const cases: [string, number, number[], number[]][] = [
  ["four-jobs", 2, [1, 2, 3, 6], [0, 1, 7, 8]],
  ["long-runs", 3, [27, 97, 871], [111, 118, 178]],
  ["empty", 2, [], []],
  ["one-worker", 1, [7, 8, 9], [16, 3, 19]],
  ["more-workers-than-jobs", 8, [5, 6], [5, 8]],
  ["duplicates", 3, [27, 27, 27, 1], [111, 111, 111, 0]],
  ["wide-intermediate", 2, [113383, 837799], [247, 524]],
  ["many", 4, many, many.map(steps)],
];

for (const [name, workers, numbers, want] of cases) {
  test(name, async () => {
    assert.deepEqual(await stepsOnPool(workers, numbers), want);
  });
}
pool.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

// Package pool sends one job for each number to a fixed set of worker goroutines
// and collects the results in order.
package pool

import "sync"

func collatzSteps(n int64) int {
	steps := 0
	for n != 1 {
		if n%2 == 0 {
			n /= 2
		} else {
			n = 3*n + 1
		}
		steps++
	}
	return steps
}

// StepsOnPool returns the step count of each number, in the order of numbers.
func StepsOnPool(workers int, numbers []int) []int {
	results := make([]int, len(numbers))
	jobs := make(chan int) // indexes into numbers
	var wg sync.WaitGroup
	for range workers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			// The loop ends when jobs is closed and empty.
			for i := range jobs {
				results[i] = collatzSteps(int64(numbers[i])) // each job writes its own element
			}
		}()
	}
	for i := range numbers {
		jobs <- i
	}
	close(jobs)
	wg.Wait()
	return results
}
pool_test.go 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

package pool

import (
	"slices"
	"testing"
)

func TestStepsOnPool(t *testing.T) {
	var many, manyWant []int
	for n := 1; n <= 200; n++ {
		many = append(many, n)
		manyWant = append(manyWant, collatzSteps(int64(n)))
	}
	cases := []struct {
		name    string
		workers int
		numbers []int
		want    []int
	}{
		{"four-jobs", 2, []int{1, 2, 3, 6}, []int{0, 1, 7, 8}},
		{"long-runs", 3, []int{27, 97, 871}, []int{111, 118, 178}},
		{"empty", 2, []int{}, []int{}},
		{"one-worker", 1, []int{7, 8, 9}, []int{16, 3, 19}},
		{"more-workers-than-jobs", 8, []int{5, 6}, []int{5, 8}},
		{"duplicates", 3, []int{27, 27, 27, 1}, []int{111, 111, 111, 0}},
		{"wide-intermediate", 2, []int{113383, 837799}, []int{247, 524}},
		{"many", 4, many, manyWant},
	}
	for _, c := range cases {
		if got := StepsOnPool(c.workers, c.numbers); !slices.Equal(got, c.want) {
			t.Errorf("case %s: got %v, want %v", c.name, got, c.want)
		}
	}
}
pool.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

//! Sends one job for each number to a fixed set of worker threads through a shared queue,
//! and collects the results in order.

use std::sync::{mpsc, Mutex};
use std::thread;

/// Returns the number of steps that take n to 1.
pub fn collatz_steps(mut n: u64) -> u32 {
    let mut steps = 0;
    while n != 1 {
        n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
        steps += 1;
    }
    steps
}

/// Returns the step count of each number, in the order of numbers.
/// Panics if a worker thread cannot be created.
pub fn steps_on_pool(workers: usize, numbers: &[u32]) -> Vec<u32> {
    let (job_tx, job_rx) = mpsc::channel::<usize>();
    let (result_tx, result_rx) = mpsc::channel::<(usize, u32)>();
    for i in 0..numbers.len() {
        job_tx.send(i).expect("the queue is open");
    }
    // With the sender gone, recv returns an error when the queue is empty, and the workers stop.
    drop(job_tx);
    // Several workers share one receiver, so it is behind a mutex.
    let job_rx = Mutex::new(job_rx);
    // The scope joins every worker before it returns.
    thread::scope(|s| {
        for _ in 0..workers {
            let job_rx = &job_rx;
            let result_tx = result_tx.clone();
            s.spawn(move || loop {
                // The lock guard is a temporary of this let statement, so the lock is free again
                // before the job runs.
                let job = job_rx.lock().expect("no worker panicked").recv();
                match job {
                    Ok(i) => {
                        let steps = collatz_steps(u64::from(numbers[i]));
                        result_tx.send((i, steps)).expect("the result queue is open");
                    }
                    Err(_) => break,
                }
            });
        }
    });
    drop(result_tx);
    let mut results = vec![0; numbers.len()];
    for (i, steps) in result_rx {
        results[i] = steps;
    }
    results
}
tests/pool_test.rs 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/run-tasks-on-a-thread-pool/.

use algo_run_tasks_on_a_thread_pool::{collatz_steps, steps_on_pool};

#[test]
fn cases() {
    let many: Vec<u32> = (1..=200).collect();
    let many_want: Vec<u32> = many.iter().map(|&n| collatz_steps(u64::from(n))).collect();
    let cases: Vec<(&str, usize, Vec<u32>, Vec<u32>)> = vec![
        ("four-jobs", 2, vec![1, 2, 3, 6], vec![0, 1, 7, 8]),
        ("long-runs", 3, vec![27, 97, 871], vec![111, 118, 178]),
        ("empty", 2, vec![], vec![]),
        ("one-worker", 1, vec![7, 8, 9], vec![16, 3, 19]),
        ("more-workers-than-jobs", 8, vec![5, 6], vec![5, 8]),
        ("duplicates", 3, vec![27, 27, 27, 1], vec![111, 111, 111, 0]),
        ("wide-intermediate", 2, vec![113383, 837799], vec![247, 524]),
        ("many", 4, many, many_want),
    ];
    for (name, workers, numbers, want) in cases {
        assert_eq!(steps_on_pool(workers, &numbers), want, "case {name}");
    }
}

References

  1. The Python Standard Library, concurrent.futures, ThreadPoolExecutor; ProcessPoolExecutor
  2. Java SE 21 API, java.util.concurrent.Executors, newFixedThreadPool(int)
  3. Java SE 21 API, java.util.concurrent.ExecutorService, shutdown(); close(); invokeAll
  4. Microsoft Learn, The managed thread pool, Thread pool characteristics
  5. Microsoft Learn, ParallelOptions.MaxDegreeOfParallelism, Remarks
  6. Microsoft Learn, How to write a simple Parallel.For loop, Return Value and Exception Handling
  7. Go by Example, Worker Pools, whole page
  8. The Rust Programming Language, Turning Our Single-Threaded Server into a Multithreaded Server, Improving Throughput with a Thread Pool; Listing 21-21
  9. Rust standard library, module std::sync::mpsc, Disconnection
  10. POSIX.1-2024, pthread_mutex_lock, DESCRIPTION
  11. std::packaged_task, cppreference.com, the class description
  12. Node.js documentation, Worker threads, new Worker(filename[, options]) example
  13. The Python Standard Library, threading, CPython implementation detail
  14. rayon crate documentation, crate overview
  15. Java SE 21 API, java.util.concurrent.ThreadPoolExecutor, Queuing

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source