Taskintro
Wait for threads to finish
Also called join threads, wait for all threads, join all threads, WaitGroup example, Task.WhenAll example, Promise.all workers, collect results from threads, fork-join, pthread_join example.
Sum each chunk of numbers on its own thread, start all threads before waiting, wait until every thread has finished, and return the sums in the order of the chunks.
- Evidence
- Code in 9 languages
Task
Write a function parallel_sums(chunks) that gets a list of chunks, each a list of integers. The function sums each chunk on a thread other than the caller. It starts the work for all chunks before it waits for any of them. Then it waits until every thread has finished and returns the sums, in the order of the chunks. For example, parallel_sums([[1, 2, 3], [4, 5]]) is [6, 9].
There are 0 to 32 chunks. Each chunk has 0 to 10,000 items, and each item has an absolute value of 10^9 or less, so a sum needs 64 bits. The task is about the wait: how the caller knows that all threads are done, how it gets their results, and what it sees when a thread fails. Start a thread is about the start.
Solutions
| Language | Start | Wait for all | Results |
|---|---|---|---|
| Python | ThreadPoolExecutor.submit |
the end of the with block |
Future.result() |
| JavaScript | new Worker for each chunk |
Promise.all |
the array that the promise gives |
| TypeScript | as JavaScript | as JavaScript | as JavaScript |
| Java | Thread.ofPlatform().start |
join() on each thread |
an array slot for each thread |
| C# | Task.Run |
Task.WhenAll |
the array that WhenAll gives |
| Go | go with wg.Add(1) and wg.Done() |
WaitGroup.Wait |
a slice element for each goroutine |
| Rust | Scope::spawn in thread::scope |
the end of the scope, or join() |
the value that join() returns |
| C | pthread_create |
pthread_join on each thread |
the pointer that the thread returns |
| C++ | std::jthread |
the destructor of each std::jthread |
a vector slot for each thread |
- C waits with
pthread_join, which suspends the caller "until the target thread terminates, unless the target thread has already terminated".1 The value that the thread returns comes back through the second argument. The solution returns a pointer to the sum in the job struct of the thread. - C++ has
join(), and "The completion of the thread identified by *this synchronizes with the corresponding successful return from join()".2 The solution usesstd::jthread, which has the same general behavior asstd::threadbut "automatically rejoins on destruction".3 The threads live in a block, and the end of the block joins all of them. - Python uses a
ThreadPoolExecutorwith one worker for each chunk. Leaving thewithblock shuts the executor down and waits, "as if Executor.shutdown() were called with wait set to True".4Future.result()returns the value of the call. "If the call raised an exception, this method will raise the same exception."4 - Java calls
join()on each thread. It "Waits for this thread to terminate".5 Each thread writes its own element of an array, and the caller reads the array after all joins. - Go uses a
sync.WaitGroup. A WaitGroup "is a counting semaphore typically used to wait for a group of goroutines or tasks to finish".6 The caller callsAdd(1)before eachgostatement, each goroutine callsDonewhen it returns, andWaitblocks until the counter is zero.6 - Rust uses
thread::scope. All threads of the scope "will be automatically joined before this function returns", so they can borrowchunkswithout'staticdata.7JoinHandle::joingives the return value of each thread, and the completion of the thread "synchronizes with this function returning".8 - C# queues each sum with
Task.Runand waits withTask.WhenAll. When no task fails, the result ofWhenAllis "an array containing all of the results of the supplied tasks in the same order as they were provided".9 The tasks run on threads of the thread pool, not on new threads. - JavaScript and TypeScript start one Node.js worker for each chunk and wrap its message in a promise.
Promise.allkeeps the order of the promises. The function returns a promise, because the main thread does not block.
Alternatives
- A countdown latch. Java's
CountDownLatchand C++'sstd::latchstart at the number of threads. Each thread counts down once, and the caller waits for zero. The threads do not need handles. - A join with a time limit. Python's
join(timeout)always returnsNone, so the caller must callis_alive()after it to see whether the time ran out.10 Java hasjoin(Duration), which returns aboolean.5 - Results through a channel. In Go, each goroutine can send its sum on a channel, with its index. The caller receives one value for each goroutine, so it needs no WaitGroup. See Channel.
- A group that cancels on error. The Go
WaitGroupgives no error back. Go by Example says that this approach "has no straightforward way to propagate errors from workers" and points to theerrgrouppackage.11
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: no chunks start no threads and give an empty list. Python'sThreadPoolExecutorneeds at least one worker, so the solution returns early.empty-chunk: an empty chunk has the sum 0. The thread for it still starts and must still be joined.single: one chunk, one thread.negative: negative numbers sum as usual.limit: 3 × 10^9 does not fit in a 32-bitint. The solutions use 64-bit integers; JavaScript numbers hold such sums exactly.many: 32 threads run at the same time, and the sums must come back in the order of the chunks, not in the order in which the threads finish.
Pitfalls
- A join right after each start. A loop that starts a thread and joins it at once runs the threads one after another. Start all threads first, then join them. Here a
Barrierlets three threads pass only when all three are at it at the same time:
import threading
def threads_that_met(start_all_first):
barrier = threading.Barrier(3, timeout=1.0)
met = []
def work(i):
try:
barrier.wait()
met.append(i)
except threading.BrokenBarrierError:
pass
threads = [threading.Thread(target=work, args=(i,)) for i in range(3)]
if start_all_first:
for t in threads:
t.start()
for t in threads:
t.join()
else:
for t in threads:
t.start()
t.join()
return len(met)
print("start all, then join:", threads_that_met(True))
print("join after each start:", threads_that_met(False))
start all, then join: 3
join after each start: 0
With a join after each start, the first thread waits alone at the barrier until the timeout breaks it.
- Errors that disappear. An exception in the function of a Python
Threaddoes not reachjoin().threading.excepthook()handles it, and by default it prints the exception onsys.stderr.10Future.result()raises it again in the caller.4 In C#, the task fromWhenAllfaults when any task faults, and its exceptions hold all of them.9 - Joining the current thread. A thread that joins itself waits forever. Python's
join()raisesRuntimeErrorinstead, "as that would cause a deadlock".10 - Two joins of one thread. POSIX says that the results of multiple simultaneous calls of
pthread_joinon the same thread are undefined.1 In C++, concurrent calls ofjoin()on one thread object are a data race.2 Give each thread one owner that joins it. - A
WaitGroupthat counts too late. The calls toAdd"should execute before the statement creating the goroutine or other event to be waited for".6 If a goroutine callsAdditself, the caller can reachWaitfirst and miss it. CallAddin the caller, then start the goroutine. - Blocking where the caller must not block.
Task.WhenAlldoes not block the calling thread, but itsResultdoes.9 In code that is already asynchronous,awaitthe task in place of a blocking wait.
Related tasks
- Start a thread starts one thread for each item and passes it its argument.
- Join and detach explains joinable and detached threads and the end of the program.
- Futures and promises are handles that hold the result of a job that runs elsewhere.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
"""Sum each chunk on its own worker thread, wait for all of them and collect the sums."""
from concurrent.futures import ThreadPoolExecutor
def parallel_sums(chunks: list[list[int]]) -> list[int]:
if not chunks:
return []
# One worker thread for each chunk. Leaving the with block waits for all of them.
with ThreadPoolExecutor(max_workers=len(chunks)) as executor:
futures = [executor.submit(sum, chunk) for chunk in chunks]
# Every future is done here; result() returns the sum, or raises the exception of the call.
return [future.result() for future in futures]
test_sums.py 31 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
import threading
import pytest
from sums import parallel_sums
CASES = {
"two": ([[1, 2, 3], [4, 5]], [6, 9]),
"three": ([[10], [20, 30], [-5, 5]], [10, 50, 0]),
"empty": ([], []),
"empty-chunk": ([[], [7]], [0, 7]),
"single": ([[42]], [42]),
"negative": ([[-1, -2], [-3]], [-3, -3]),
"limit": ([[10**9] * 3, [-(10**9)] * 3], [3 * 10**9, -3 * 10**9]),
"many": ([[i, i, i] for i in range(32)], [3 * i for i in range(32)]),
}
@pytest.mark.parametrize("name", CASES)
def test_parallel_sums(name):
chunks, want = CASES[name]
assert parallel_sums(chunks) == want
def test_all_threads_have_finished():
before = threading.active_count()
parallel_sums([[i] for i in range(8)])
assert threading.active_count() == before
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
#include "sums.hpp"
#include <cstddef>
#include <numeric>
#include <thread>
namespace sums {
std::vector<std::int64_t> parallel_sums(const std::vector<std::vector<std::int64_t>>& chunks) {
std::vector<std::int64_t> results(chunks.size());
{
std::vector<std::jthread> threads;
threads.reserve(chunks.size());
for (std::size_t i = 0; i < chunks.size(); i++) {
threads.emplace_back([&results, &chunks, i] {
results[i] = std::accumulate(chunks[i].begin(), chunks[i].end(), std::int64_t{0});
});
}
// The destructor of each std::jthread joins its thread, here and also when emplace_back throws.
}
return results;
}
} // namespace sums
sums.hpp 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
#pragma once
#include <cstdint>
#include <vector>
namespace sums {
// Sums each chunk on its own std::jthread, waits for all of them and returns the sums in order.
// Throws std::system_error if a thread cannot be started.
std::vector<std::int64_t> parallel_sums(const std::vector<std::vector<std::int64_t>>& chunks);
} // namespace sums
test_sums.cpp 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
#include "sums.hpp"
#include <cstdint>
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<std::vector<std::int64_t>>& chunks,
const std::vector<std::int64_t>& want) {
if (sums::parallel_sums(chunks) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
const std::int64_t g = 1000000000;
check("two", {{1, 2, 3}, {4, 5}}, {6, 9});
check("three", {{10}, {20, 30}, {-5, 5}}, {10, 50, 0});
check("empty", {}, {});
check("empty-chunk", {{}, {7}}, {0, 7});
check("single", {{42}}, {42});
check("negative", {{-1, -2}, {-3}}, {-3, -3});
check("limit", {{g, g, g}, {-g, -g, -g}}, {3 * g, -3 * g});
std::vector<std::vector<std::int64_t>> many;
std::vector<std::int64_t> want;
for (std::int64_t i = 0; i < 32; i++) {
many.push_back({i, i, i});
want.push_back(3 * i);
}
check("many", many, want);
if (failures == 0) {
std::cout << "all tests passed\n";
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
/** Sums each chunk on its own thread, waits for all of them and collects the sums. */
public final class Sums {
private Sums() {}
public static long[] parallelSums(long[][] chunks) throws InterruptedException {
long[] sums = new long[chunks.length];
Thread[] threads = new Thread[chunks.length];
for (int i = 0; i < chunks.length; i++) {
int index = i;
threads[i] =
Thread.ofPlatform()
.start(
() -> {
long sum = 0;
for (long n : chunks[index]) {
sum += n;
}
sums[index] = sum;
});
}
// Wait for every thread. The end of a thread happens-before the return of its join().
for (Thread thread : threads) {
thread.join();
}
return sums;
}
}
SumsTest.java 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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 SumsTest {
static Stream<Arguments> cases() {
long[][] many = IntStream.range(0, 32).mapToObj(i -> new long[] {i, i, i}).toArray(long[][]::new);
long[] manyWant = IntStream.range(0, 32).mapToLong(i -> 3L * i).toArray();
long g = 1_000_000_000L;
return Stream.of(
Arguments.of("two", new long[][] {{1, 2, 3}, {4, 5}}, new long[] {6, 9}),
Arguments.of("three", new long[][] {{10}, {20, 30}, {-5, 5}}, new long[] {10, 50, 0}),
Arguments.of("empty", new long[][] {}, new long[] {}),
Arguments.of("empty-chunk", new long[][] {{}, {7}}, new long[] {0, 7}),
Arguments.of("single", new long[][] {{42}}, new long[] {42}),
Arguments.of("negative", new long[][] {{-1, -2}, {-3}}, new long[] {-3, -3}),
Arguments.of("limit", new long[][] {{g, g, g}, {-g, -g, -g}}, new long[] {3 * g, -3 * g}),
Arguments.of("many", many, manyWant));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void parallelSums(String name, long[][] chunks, long[] want) throws InterruptedException {
assertArrayEquals(want, Sums.parallelSums(chunks), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
#include "sums.h"
#include <pthread.h>
#include <stdlib.h>
struct job {
const long long *items;
size_t length;
long long sum;
};
static void *sum_chunk(void *arg) {
struct job *job = arg;
job->sum = 0;
for (size_t i = 0; i < job->length; i++) {
job->sum += job->items[i];
}
// pthread_join hands this pointer to the caller.
return &job->sum;
}
bool parallel_sums(const long long *const chunks[], const size_t lengths[], size_t n, long long out[]) {
struct job *jobs = calloc(n > 0 ? n : 1, sizeof *jobs);
pthread_t *threads = calloc(n > 0 ? n : 1, sizeof *threads);
if (jobs == NULL || threads == NULL) {
free(jobs);
free(threads);
return false;
}
size_t started = 0;
for (; started < n; started++) {
jobs[started] = (struct job){chunks[started], lengths[started], 0};
if (pthread_create(&threads[started], NULL, sum_chunk, &jobs[started]) != 0) {
break;
}
}
// Join every thread that started, even after a failure, before the jobs are freed.
for (size_t i = 0; i < started; i++) {
void *result = NULL;
pthread_join(threads[i], &result);
out[i] = *(long long *)result;
}
free(jobs);
free(threads);
return started == n;
}
sums.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
#ifndef SUMS_H
#define SUMS_H
#include <stdbool.h>
#include <stddef.h>
// Sums each of the n chunks on its own thread; chunk i has lengths[i] items.
// Waits for all threads and writes sum i to out[i]. Returns false if a thread cannot be created.
bool parallel_sums(const long long *const chunks[], const size_t lengths[], size_t n, long long out[]);
#endif
test_sums.c 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
#include "sums.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *name, const long long *const chunks[], const size_t lengths[], size_t n,
const long long want[]) {
long long got[32] = {0};
if (!parallel_sums(chunks, lengths, n, got)) {
fprintf(stderr, "case %s failed: a thread 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 %lld, want %lld\n", name, i, got[i], want[i]);
failures++;
return;
}
}
}
int main(void) {
const long long g = 1000000000;
check("two", (const long long *[]){(long long[]){1, 2, 3}, (long long[]){4, 5}}, (size_t[]){3, 2}, 2,
(long long[]){6, 9});
check("three", (const long long *[]){(long long[]){10}, (long long[]){20, 30}, (long long[]){-5, 5}},
(size_t[]){1, 2, 2}, 3, (long long[]){10, 50, 0});
check("empty", NULL, NULL, 0, NULL);
check("empty-chunk", (const long long *[]){NULL, (long long[]){7}}, (size_t[]){0, 1}, 2, (long long[]){0, 7});
check("single", (const long long *[]){(long long[]){42}}, (size_t[]){1}, 1, (long long[]){42});
check("negative", (const long long *[]){(long long[]){-1, -2}, (long long[]){-3}}, (size_t[]){2, 1}, 2,
(long long[]){-3, -3});
check("limit", (const long long *[]){(long long[]){g, g, g}, (long long[]){-g, -g, -g}}, (size_t[]){3, 3}, 2,
(long long[]){3 * g, -3 * g});
long long items[32][3], want[32];
const long long *many[32];
size_t lengths[32];
for (int i = 0; i < 32; i++) {
items[i][0] = items[i][1] = items[i][2] = i;
many[i] = items[i];
lengths[i] = 3;
want[i] = 3LL * i;
}
check("many", many, lengths, 32, want);
if (failures == 0) {
printf("all tests passed\n");
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
using System.Linq;
using System.Threading.Tasks;
/// <summary>Sums each chunk on a thread-pool thread, waits for all of them and collects the sums.</summary>
public static class Sums
{
public static long[] ParallelSums(long[][] chunks)
{
// Task.Run queues each sum to the thread pool and returns a Task<long> at once.
Task<long>[] tasks = chunks.Select(chunk => Task.Run(() => chunk.Sum())).ToArray();
// WhenAll completes when every task has completed; its result keeps the order of the tasks.
return Task.WhenAll(tasks).GetAwaiter().GetResult();
}
}
SumsTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
using System.Linq;
using Xunit;
public sealed class SumsTests
{
private const long G = 1_000_000_000;
public static TheoryData<string, long[][], long[]> Cases => new()
{
{ "two", new[] { new long[] { 1, 2, 3 }, new long[] { 4, 5 } }, new long[] { 6, 9 } },
{ "three", new[] { new long[] { 10 }, new long[] { 20, 30 }, new long[] { -5, 5 } }, new long[] { 10, 50, 0 } },
{ "empty", new long[][] { }, new long[] { } },
{ "empty-chunk", new[] { new long[] { }, new long[] { 7 } }, new long[] { 0, 7 } },
{ "single", new[] { new long[] { 42 } }, new long[] { 42 } },
{ "negative", new[] { new long[] { -1, -2 }, new long[] { -3 } }, new long[] { -3, -3 } },
{ "limit", new[] { new long[] { G, G, G }, new long[] { -G, -G, -G } }, new long[] { 3 * G, -3 * G } },
{ "many", Enumerable.Range(0, 32).Select(i => new long[] { i, i, i }).ToArray(),
Enumerable.Range(0, 32).Select(i => 3L * i).ToArray() },
};
[Theory]
[MemberData(nameof(Cases))]
public void ParallelSums(string name, long[][] chunks, long[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Sums.ParallelSums(chunks));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
// Sum each chunk on its own worker thread, wait for all of them and collect the sums.
import { Worker } from "node:worker_threads";
const source = `
const { parentPort, workerData } = require("node:worker_threads");
let sum = 0;
for (const n of workerData) sum += n;
parentPort.postMessage(sum);
`;
function sumOnWorker(chunk) {
return new Promise((resolve, reject) => {
const worker = new Worker(source, { eval: true, workerData: chunk });
worker.once("message", resolve);
worker.once("error", reject);
});
}
// Returns a promise of the sums, in the order of chunks.
export function parallelSums(chunks) {
// Promise.all settles after every worker has sent its sum, and keeps the order of the input.
return Promise.all(chunks.map(sumOnWorker));
}
sums.test.js 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { parallelSums } from "./sums.js";
const many = Array.from({ length: 32 }, (_, i) => [i, i, i]);
const cases = [
["two", [[1, 2, 3], [4, 5]], [6, 9]],
["three", [[10], [20, 30], [-5, 5]], [10, 50, 0]],
["empty", [], []],
["empty-chunk", [[], [7]], [0, 7]],
["single", [[42]], [42]],
["negative", [[-1, -2], [-3]], [-3, -3]],
["limit", [[1e9, 1e9, 1e9], [-1e9, -1e9, -1e9]], [3e9, -3e9]],
["many", many, many.map((c) => c[0] * 3)],
];
for (const [name, chunks, want] of cases) {
test(name, async () => {
assert.deepEqual(await parallelSums(chunks), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
// Sum each chunk on its own worker thread, wait for all of them and collect the sums.
import { Worker } from "node:worker_threads";
const source = `
const { parentPort, workerData } = require("node:worker_threads");
let sum = 0;
for (const n of workerData) sum += n;
parentPort.postMessage(sum);
`;
function sumOnWorker(chunk: readonly number[]): Promise<number> {
return new Promise((resolve, reject) => {
const worker = new Worker(source, { eval: true, workerData: chunk });
worker.once("message", (sum: number) => resolve(sum));
worker.once("error", reject);
});
}
// Returns a promise of the sums, in the order of chunks.
export function parallelSums(chunks: readonly (readonly number[])[]): Promise<number[]> {
// Promise.all settles after every worker has sent its sum, and keeps the order of the input.
return Promise.all(chunks.map(sumOnWorker));
}
sums.test.ts 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { parallelSums } from "./sums.ts";
const many = Array.from({ length: 32 }, (_, i) => [i, i, i]);
const cases: [string, number[][], number[]][] = [
["two", [[1, 2, 3], [4, 5]], [6, 9]],
["three", [[10], [20, 30], [-5, 5]], [10, 50, 0]],
["empty", [], []],
["empty-chunk", [[], [7]], [0, 7]],
["single", [[42]], [42]],
["negative", [[-1, -2], [-3]], [-3, -3]],
["limit", [[1e9, 1e9, 1e9], [-1e9, -1e9, -1e9]], [3e9, -3e9]],
["many", many, many.map((c) => c[0] * 3)],
];
for (const [name, chunks, want] of cases) {
test(name, async () => {
assert.deepEqual(await parallelSums(chunks), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
// Package sums sums each chunk on its own goroutine, waits for all of them and collects the sums.
package sums
import "sync"
// ParallelSums returns the sum of each chunk, in the order of chunks.
func ParallelSums(chunks [][]int64) []int64 {
sums := make([]int64, len(chunks))
var wg sync.WaitGroup
for i, chunk := range chunks {
// Add counts the goroutine before it starts; Done uncounts it when it returns.
wg.Add(1)
go func() {
defer wg.Done()
var sum int64
for _, n := range chunk {
sum += n
}
sums[i] = sum
}()
}
// Wait blocks until the counter is zero, that is, until every goroutine has called Done.
wg.Wait()
return sums
}
sums_test.go 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
package sums
import (
"slices"
"testing"
)
func TestParallelSums(t *testing.T) {
var many [][]int64
var manyWant []int64
for i := range int64(32) {
many = append(many, []int64{i, i, i})
manyWant = append(manyWant, 3*i)
}
cases := []struct {
name string
chunks [][]int64
want []int64
}{
{"two", [][]int64{{1, 2, 3}, {4, 5}}, []int64{6, 9}},
{"three", [][]int64{{10}, {20, 30}, {-5, 5}}, []int64{10, 50, 0}},
{"empty", [][]int64{}, []int64{}},
{"empty-chunk", [][]int64{{}, {7}}, []int64{0, 7}},
{"single", [][]int64{{42}}, []int64{42}},
{"negative", [][]int64{{-1, -2}, {-3}}, []int64{-3, -3}},
{"limit", [][]int64{{1e9, 1e9, 1e9}, {-1e9, -1e9, -1e9}}, []int64{3e9, -3e9}},
{"many", many, manyWant},
}
for _, c := range cases {
if got := ParallelSums(c.chunks); !slices.Equal(got, c.want) {
t.Errorf("case %s: got %v, want %v", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
//! Sums each chunk on its own scoped thread, waits for all of them and collects the sums.
use std::thread;
/// Returns the sum of each chunk, in the order of chunks.
/// Panics if a thread cannot be created.
pub fn parallel_sums(chunks: &[Vec<i64>]) -> Vec<i64> {
// A scope joins all its threads before it returns, so the threads may borrow chunks.
thread::scope(|s| {
let handles: Vec<_> = chunks
.iter()
.map(|chunk| s.spawn(move || chunk.iter().sum::<i64>()))
.collect();
handles
.into_iter()
.map(|handle| handle.join().expect("a summing thread panicked"))
.collect()
})
}
tests/sums_test.rs 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wait-for-threads-to-finish/.
use algo_wait_for_threads_to_finish::parallel_sums;
#[test]
fn cases() {
let g = 1_000_000_000;
let cases: Vec<(&str, Vec<Vec<i64>>, Vec<i64>)> = vec![
("two", vec![vec![1, 2, 3], vec![4, 5]], vec![6, 9]),
("three", vec![vec![10], vec![20, 30], vec![-5, 5]], vec![10, 50, 0]),
("empty", vec![], vec![]),
("empty-chunk", vec![vec![], vec![7]], vec![0, 7]),
("single", vec![vec![42]], vec![42]),
("negative", vec![vec![-1, -2], vec![-3]], vec![-3, -3]),
("limit", vec![vec![g; 3], vec![-g; 3]], vec![3 * g, -3 * g]),
("many", (0..32).map(|i| vec![i; 3]).collect(), (0..32).map(|i| 3 * i).collect()),
];
for (name, chunks, want) in cases {
assert_eq!(parallel_sums(&chunks), want, "case {name}");
}
}
References
- POSIX.1-2024, pthread_join, DESCRIPTION
- std::thread::join, cppreference.com, the description
- std::jthread, cppreference.com, the class description
- The Python Standard Library, concurrent.futures, Executor.shutdown; Future.result
- Java SE 21 API, java.lang.Thread, join(), join(long), join(Duration)
- Go standard library, package sync, type WaitGroup; WaitGroup.Go; WaitGroup.Wait
- The Rust Standard Library, Function std::thread::scope, the function description
- The Rust Standard Library, Struct std::thread::JoinHandle, join
- .NET API reference, Task.WhenAll Method, the summary; Remarks of WhenAll<TResult>(IEnumerable<Task<TResult>>)
- The Python Standard Library, threading, Thread objects; join(); run()
- Go by Example, WaitGroups, the notes after the example
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 6C4496 Edit this page History Report an error Markdown