Programming Search⌘K

Taskintro

Start a thread

Also called create a thread, spawn a thread, launch a thread, run a function on a new thread, pthread_create example, std::thread example, start a goroutine, Thread.start.

Start one thread for each name, pass the name to it as an argument, let each thread build a greeting in its own slot, and wait for all threads before returning the greetings.

Task

Write a function thread_greetings(names) that starts one new thread for each name. Pass the name to the thread as its argument. The thread builds the string "hello from " + name and stores it in its own slot of a result list. After it has started all the threads, the function waits for each of them and returns the list, in the order of the names. For example, thread_greetings(["Ada", "Linus"]) is ["hello from Ada", "hello from Linus"].

The list has 0 to 64 names, and each name has 0 to 50 characters. The task is about the start of a thread: the function to run, the argument, and the place where the thread puts its result. Wait for threads to finish is about the wait. The plan of the task asks for two threads that print. Two threads that print at the same time print in an order that changes from run to run, so the threads here build strings and the caller checks them.

Solutions

Language Start a thread Pass the argument Get the result back
Python threading.Thread(target=f, args=(...)).start() args a slot of a list, read after join()
JavaScript new Worker(source, { workerData }) workerData, a copy postMessage, wrapped in a promise
TypeScript as JavaScript as JavaScript as JavaScript
Java Thread.ofPlatform().start(runnable) a lambda captures a local an array slot, read after join()
C# new Thread(lambda).Start() a lambda captures a local an array slot, read after Join()
Go go f() with a sync.WaitGroup a closure a slice element, read after Wait()
Rust std::thread::spawn(move || ...) the closure owns a copy the return value, from join()
C pthread_create(&id, NULL, f, arg) one void * a field of the argument struct
C++ std::thread(lambda) a lambda captures a copy a vector slot, read after join()
  • C gives the thread one argument. pthread_create creates a thread that executes start_routine "with arg as its sole argument".1 The solution passes a pointer to a struct that holds the name and a field for the greeting. Each thread gets its own struct, so no two threads write the same memory.
  • C++ starts the thread when the std::thread object is made: "Threads begin execution immediately upon construction of the associated thread object".2 The return value of the function is ignored, so the thread writes its result to its own element of a vector.
  • Java has the Thread.Builder API. Thread.ofPlatform().start(runnable) makes an operating system thread and starts it. The new thread "executes concurrently with the thread that caused it to start".3
  • Python gives the function to run as target and its arguments as args. start() arranges for the run() method of the object "to be invoked in a separate thread of control".4
  • Go starts a goroutine with the go statement. The statement "starts the execution of a function call as an independent concurrent thread of control, or goroutine, within the same address space".5 The results of the function are discarded, so the goroutine writes to its own element of a slice. The caller calls wg.Add(1) before each go statement, and the goroutine calls wg.Done() when it returns, so that Wait() can wait for it. The calls to Add "should execute before the statement creating the goroutine".6
  • Rust starts a thread with thread::spawn, which returns a JoinHandle.7 The closure must be 'static and Send, because the thread can outlive the function that started it. The solution gives each closure its own String with move. The thread returns the greeting, and join() hands it to the caller.
  • C# starts a Thread with a delegate. A method with an argument can use a ParameterizedThreadStart delegate, which takes an object.8 A lambda that captures typed locals is simpler, and the solution uses it.
  • JavaScript and TypeScript have no threads that share memory. In Node.js, node:worker_threads "enables the use of threads that execute JavaScript in parallel".9 The value in workerData is cloned with the structured clone algorithm, so the worker gets a copy of the name.9 The worker sends the greeting back with postMessage. The function returns a promise, because the main thread cannot block to wait for a worker.

Alternatives

  • A thread pool. For many small jobs, a pool such as Java's ExecutorService or Python's ThreadPoolExecutor reuses a few threads. A new thread for each job costs more than the job here.
  • Scoped threads. Rust's thread::scope and C++'s std::jthread join their threads at the end of a block. Then a thread can borrow local data, and the caller cannot forget the join. Wait for threads to finish uses them.
  • A future. C++'s std::async, C#'s Task.Run and Java's ExecutorService.submit return a handle that holds the result of the function. The caller does not need a result slot.

Edge cases

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

  • empty: no names start no threads and give an empty list. In C, the code must not call calloc with a size of 0 and then treat the result as an error.
  • single: one thread.
  • empty-name: the empty name gives "hello from ", with the space.
  • duplicate: two equal names still start two threads and give two greetings.
  • unicode: names with characters outside ASCII pass through unchanged. In C the strings are UTF-8 bytes.
  • many: 32 names start 32 threads that run at the same time. Each thread must write only its own slot.

Pitfalls

  • Calling run() in place of start(). In Python and Java, run() is a plain method call. It runs the function on the calling thread, and no new thread starts:
import threading


def where():
    print("ran on", threading.current_thread().name)


plain = threading.Thread(target=where, name="greeter-1")
plain.run()
started = threading.Thread(target=where, name="greeter-2")
started.start()
started.join()
Output
ran on MainThread
ran on greeter-2

Python's start() must be called at most once for each thread object, and a second call raises RuntimeError.4

  • One shared variable for all threads. In C, passing &i of a loop counter to every thread gives all threads the same address, and they read whatever value it has when they run. Give each thread its own struct. In Go before version 1.22, all iterations of a for loop shared one loop variable. Now "Each iteration has its own separate declared variable".5 In C#, a lambda in a for loop captures the one variable i, so the solution copies it to index first.
  • Reading the result before the wait. The thread may not have run yet. Read a result only after join(), Wait() or the promise. The join also makes the writes of the thread visible to the caller.
  • A program that ends first. In Go, when main returns, the program exits. "It does not wait for other (non-main) goroutines to complete."5
  • Destroying a running std::thread. If a std::thread is still joinable when it is destroyed, the destructor calls std::terminate.10 The C++ solution joins the threads that it started, also when a later start throws.
  • Workers for small jobs. A Node.js worker starts a new JavaScript engine instance. Workers "are useful for performing CPU-intensive JavaScript operations", and "They do not help much with I/O-intensive work."9

Code

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

greetings.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/start-a-thread/.

"""Start one thread per name; each thread builds the greeting for its name."""

import threading


def _greet(name: str, results: list[str], index: int) -> None:
    # Runs on the new thread. It writes only its own slot of the list.
    results[index] = f"hello from {name}"


def thread_greetings(names: list[str]) -> list[str]:
    results = [""] * len(names)
    threads = [
        threading.Thread(target=_greet, args=(name, results, i), name=f"greeter-{i}")
        for i, name in enumerate(names)
    ]
    for thread in threads:
        thread.start()
    # Start all threads first, then wait for each one, so that they can run at the same time.
    for thread in threads:
        thread.join()
    return results
test_greetings.py 33 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/start-a-thread/.

import threading

import pytest

from greetings import thread_greetings

MANY = [f"t{i}" for i in range(32)]

CASES = {
    "two": (["Ada", "Linus"], ["hello from Ada", "hello from Linus"]),
    "three": (["main", "worker", "logger"], ["hello from main", "hello from worker", "hello from logger"]),
    "empty": ([], []),
    "single": (["solo"], ["hello from solo"]),
    "empty-name": ([""], ["hello from "]),
    "duplicate": (["twin", "twin"], ["hello from twin", "hello from twin"]),
    "unicode": (["Zoë", "李雷"], ["hello from Zoë", "hello from 李雷"]),
    "many": (MANY, [f"hello from {n}" for n in MANY]),
}


@pytest.mark.parametrize("name", CASES)
def test_thread_greetings(name):
    names, want = CASES[name]
    assert thread_greetings(names) == want


def test_no_thread_is_left_running():
    before = threading.active_count()
    thread_greetings(MANY)
    assert threading.active_count() == before
greetings.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

#include "greetings.hpp"

#include <cstddef>
#include <thread>

namespace greetings {

std::vector<std::string> thread_greetings(const std::vector<std::string_view>& names) {
    std::vector<std::string> results(names.size());
    std::vector<std::thread> threads;
    threads.reserve(names.size());
    try {
        for (std::size_t i = 0; i < names.size(); i++) {
            // The lambda gets copies of i and the name; it writes only its own slot.
            threads.emplace_back([&results, i, name = names[i]] { results[i] = "hello from " + std::string(name); });
        }
    } catch (...) {
        // A joinable std::thread must not be destroyed, so join the started threads first.
        for (auto& thread : threads) {
            thread.join();
        }
        throw;
    }
    // Start all threads first, then wait for each one.
    for (auto& thread : threads) {
        thread.join();
    }
    return results;
}

}  // namespace greetings
greetings.hpp 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

#pragma once

#include <string>
#include <string_view>
#include <vector>

namespace greetings {

// Starts one thread per name; thread i builds "hello from " + names[i].
// Throws std::system_error if a thread cannot be started.
std::vector<std::string> thread_greetings(const std::vector<std::string_view>& names);

}  // namespace greetings
test_greetings.cpp 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

#include "greetings.hpp"

#include <iostream>
#include <string>
#include <string_view>
#include <vector>

static int failures = 0;

static void check(std::string_view name, const std::vector<std::string_view>& names,
                  const std::vector<std::string>& want) {
    if (greetings::thread_greetings(names) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("two", {"Ada", "Linus"}, {"hello from Ada", "hello from Linus"});
    check("three", {"main", "worker", "logger"}, {"hello from main", "hello from worker", "hello from logger"});
    check("empty", {}, {});
    check("single", {"solo"}, {"hello from solo"});
    check("empty-name", {""}, {"hello from "});
    check("duplicate", {"twin", "twin"}, {"hello from twin", "hello from twin"});
    check("unicode", {"Zoë", "李雷"}, {"hello from Zoë", "hello from 李雷"});

    std::vector<std::string> many;
    std::vector<std::string> want;
    for (int i = 0; i < 32; i++) {
        many.push_back("t" + std::to_string(i));
        want.push_back("hello from t" + std::to_string(i));
    }
    check("many", std::vector<std::string_view>(many.begin(), many.end()), want);

    if (failures == 0) {
        std::cout << "all tests passed\n";
    }
    return failures == 0 ? 0 : 1;
}
Greetings.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/** Starts one thread per name; each thread builds the greeting for its name. */
public final class Greetings {
  private Greetings() {}

  public static List<String> threadGreetings(List<String> names) throws InterruptedException {
    String[] results = new String[names.size()];
    List<Thread> threads = new ArrayList<>();
    for (int i = 0; i < names.size(); i++) {
      // The lambda captures copies of index and name; it writes only its own slot.
      int index = i;
      String name = names.get(i);
      threads.add(Thread.ofPlatform().name("greeter-" + i).start(() -> results[index] = "hello from " + name));
    }
    // Start all threads first, then wait for each one. join() also makes the writes visible here.
    for (Thread thread : threads) {
      thread.join();
    }
    return Arrays.asList(results);
  }
}
GreetingsTest.java 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

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

import java.util.List;
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 GreetingsTest {
  static Stream<Arguments> cases() {
    List<String> many = IntStream.range(0, 32).mapToObj(i -> "t" + i).toList();
    return Stream.of(
        Arguments.of("two", List.of("Ada", "Linus"), List.of("hello from Ada", "hello from Linus")),
        Arguments.of(
            "three",
            List.of("main", "worker", "logger"),
            List.of("hello from main", "hello from worker", "hello from logger")),
        Arguments.of("empty", List.of(), List.of()),
        Arguments.of("single", List.of("solo"), List.of("hello from solo")),
        Arguments.of("empty-name", List.of(""), List.of("hello from ")),
        Arguments.of("duplicate", List.of("twin", "twin"), List.of("hello from twin", "hello from twin")),
        Arguments.of("unicode", List.of("Zoë", "李雷"), List.of("hello from Zoë", "hello from 李雷")),
        Arguments.of("many", many, many.stream().map(n -> "hello from " + n).toList()));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void threadGreetings(String name, List<String> names, List<String> want) throws InterruptedException {
    assertEquals(want, Greetings.threadGreetings(names), name);
  }
}
greetings.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

#include "greetings.h"

#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct job {
    const char *name;
    char *greeting;  // written by the thread
};

static void *greet(void *arg) {
    struct job *job = arg;
    const char *prefix = "hello from ";
    size_t size = strlen(prefix) + strlen(job->name) + 1;
    job->greeting = malloc(size);
    if (job->greeting != NULL) {
        snprintf(job->greeting, size, "%s%s", prefix, job->name);
    }
    return NULL;
}

char **thread_greetings(const char *const names[], size_t n) {
    struct job *jobs = calloc(n > 0 ? n : 1, sizeof *jobs);
    pthread_t *threads = calloc(n > 0 ? n : 1, sizeof *threads);
    char **out = calloc(n > 0 ? n : 1, sizeof *out);
    if (jobs == NULL || threads == NULL || out == NULL) {
        free(jobs);
        free(threads);
        free(out);
        return NULL;
    }
    size_t started = 0;
    for (; started < n; started++) {
        jobs[started].name = names[started];
        if (pthread_create(&threads[started], NULL, greet, &jobs[started]) != 0) {
            break;
        }
    }
    // Join every thread that started, even after a failure, so that none is left running.
    bool ok = started == n;
    for (size_t i = 0; i < started; i++) {
        pthread_join(threads[i], NULL);
        out[i] = jobs[i].greeting;
        ok = ok && out[i] != NULL;
    }
    free(jobs);
    free(threads);
    if (!ok) {
        free_greetings(out, started);
        return NULL;
    }
    return out;
}

void free_greetings(char **greetings, size_t n) {
    if (greetings == NULL) {
        return;
    }
    for (size_t i = 0; i < n; i++) {
        free(greetings[i]);
    }
    free(greetings);
}
greetings.h 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

#ifndef GREETINGS_H
#define GREETINGS_H

#include <stddef.h>

// Starts one thread for each of the n names. Thread i builds "hello from " followed by names[i].
// Returns a new array of n new strings, or NULL when a thread or the memory cannot be created.
char **thread_greetings(const char *const names[], size_t n);

// Frees the array that thread_greetings returned.
void free_greetings(char **greetings, size_t n);

#endif
test_greetings.c 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

#include "greetings.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

static void check(const char *name, const char *const names[], const char *const want[], size_t n) {
    char **got = thread_greetings(names, n);
    if (got == NULL) {
        fprintf(stderr, "case %s failed: NULL\n", name);
        failures++;
        return;
    }
    for (size_t i = 0; i < n; i++) {
        if (strcmp(got[i], want[i]) != 0) {
            fprintf(stderr, "case %s failed at %zu: got \"%s\", want \"%s\"\n", name, i, got[i], want[i]);
            failures++;
            break;
        }
    }
    free_greetings(got, n);
}

int main(void) {
    check("two", (const char *[]){"Ada", "Linus"}, (const char *[]){"hello from Ada", "hello from Linus"}, 2);
    check("three", (const char *[]){"main", "worker", "logger"},
          (const char *[]){"hello from main", "hello from worker", "hello from logger"}, 3);
    check("empty", NULL, NULL, 0);
    check("single", (const char *[]){"solo"}, (const char *[]){"hello from solo"}, 1);
    check("empty-name", (const char *[]){""}, (const char *[]){"hello from "}, 1);
    check("duplicate", (const char *[]){"twin", "twin"}, (const char *[]){"hello from twin", "hello from twin"}, 2);
    check("unicode", (const char *[]){"Zoë", "李雷"}, (const char *[]){"hello from Zoë", "hello from 李雷"}, 2);

    char names[32][8], wants[32][24];
    const char *many[32], *many_want[32];
    for (int i = 0; i < 32; i++) {
        snprintf(names[i], sizeof names[i], "t%d", i);
        snprintf(wants[i], sizeof wants[i], "hello from t%d", i);
        many[i] = names[i];
        many_want[i] = wants[i];
    }
    check("many", many, many_want, 32);

    if (failures == 0) {
        printf("all tests passed\n");
    }
    return failures == 0 ? 0 : 1;
}
Greetings.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

using System.Collections.Generic;
using System.Threading;

/// <summary>Starts one thread per name; each thread builds the greeting for its name.</summary>
public static class Greetings
{
    public static string[] ThreadGreetings(IReadOnlyList<string> names)
    {
        var results = new string[names.Count];
        var threads = new Thread[names.Count];
        for (int i = 0; i < names.Count; i++)
        {
            // A copy for each iteration: the lambda must not capture the loop variable i.
            int index = i;
            string name = names[i];
            threads[i] = new Thread(() => results[index] = "hello from " + name) { Name = "greeter-" + i };
            threads[i].Start();
        }
        // Start all threads first, then wait for each one.
        foreach (var thread in threads)
        {
            thread.Join();
        }
        return results;
    }
}
GreetingsTests.cs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

using System.Linq;
using Xunit;

public sealed class GreetingsTests
{
    private static readonly string[] Many = Enumerable.Range(0, 32).Select(i => "t" + i).ToArray();

    public static TheoryData<string, string[], string[]> Cases => new()
    {
        { "two", new[] { "Ada", "Linus" }, new[] { "hello from Ada", "hello from Linus" } },
        { "three", new[] { "main", "worker", "logger" }, new[] { "hello from main", "hello from worker", "hello from logger" } },
        { "empty", new string[] { }, new string[] { } },
        { "single", new[] { "solo" }, new[] { "hello from solo" } },
        { "empty-name", new[] { "" }, new[] { "hello from " } },
        { "duplicate", new[] { "twin", "twin" }, new[] { "hello from twin", "hello from twin" } },
        { "unicode", new[] { "Zoë", "李雷" }, new[] { "hello from Zoë", "hello from 李雷" } },
        { "many", Many, Many.Select(n => "hello from " + n).ToArray() },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void ThreadGreetings(string name, string[] names, string[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Greetings.ThreadGreetings(names));
    }
}
greetings.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

// Start one worker thread per name; each worker builds the greeting for its name.

import { Worker } from "node:worker_threads";

const source = `
const { parentPort, workerData } = require("node:worker_threads");
parentPort.postMessage("hello from " + workerData);
`;

function greetOnWorker(name) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(source, { eval: true, workerData: name });
    worker.once("message", resolve);
    worker.once("error", reject);
  });
}

// Returns a promise of the greetings, in the order of names.
export function threadGreetings(names) {
  // Each call starts a worker at once; Promise.all waits for all of them.
  return Promise.all(names.map(greetOnWorker));
}
greetings.test.js 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

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

import { threadGreetings } from "./greetings.js";

const many = Array.from({ length: 32 }, (_, i) => `t${i}`);

const cases = [
  ["two", ["Ada", "Linus"], ["hello from Ada", "hello from Linus"]],
  ["three", ["main", "worker", "logger"], ["hello from main", "hello from worker", "hello from logger"]],
  ["empty", [], []],
  ["single", ["solo"], ["hello from solo"]],
  ["empty-name", [""], ["hello from "]],
  ["duplicate", ["twin", "twin"], ["hello from twin", "hello from twin"]],
  ["unicode", ["Zoë", "李雷"], ["hello from Zoë", "hello from 李雷"]],
  ["many", many, many.map((n) => `hello from ${n}`)],
];

for (const [name, names, want] of cases) {
  test(name, async () => {
    assert.deepEqual(await threadGreetings(names), want);
  });
}
greetings.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

// Start one worker thread per name; each worker builds the greeting for its name.

import { Worker } from "node:worker_threads";

const source = `
const { parentPort, workerData } = require("node:worker_threads");
parentPort.postMessage("hello from " + workerData);
`;

function greetOnWorker(name: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const worker = new Worker(source, { eval: true, workerData: name });
    worker.once("message", (message: string) => resolve(message));
    worker.once("error", reject);
  });
}

// Returns a promise of the greetings, in the order of names.
export function threadGreetings(names: readonly string[]): Promise<string[]> {
  // Each call starts a worker at once; Promise.all waits for all of them.
  return Promise.all(names.map(greetOnWorker));
}
greetings.test.ts 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

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

import { threadGreetings } from "./greetings.ts";

const many = Array.from({ length: 32 }, (_, i) => `t${i}`);

const cases: [string, string[], string[]][] = [
  ["two", ["Ada", "Linus"], ["hello from Ada", "hello from Linus"]],
  ["three", ["main", "worker", "logger"], ["hello from main", "hello from worker", "hello from logger"]],
  ["empty", [], []],
  ["single", ["solo"], ["hello from solo"]],
  ["empty-name", [""], ["hello from "]],
  ["duplicate", ["twin", "twin"], ["hello from twin", "hello from twin"]],
  ["unicode", ["Zoë", "李雷"], ["hello from Zoë", "hello from 李雷"]],
  ["many", many, many.map((n) => `hello from ${n}`)],
];

for (const [name, names, want] of cases) {
  test(name, async () => {
    assert.deepEqual(await threadGreetings(names), want);
  });
}
greetings.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

// Package greetings starts one goroutine per name; each goroutine builds the greeting for its name.
package greetings

import "sync"

// ThreadGreetings returns "hello from " + names[i] for each i, each built on its own goroutine.
func ThreadGreetings(names []string) []string {
	results := make([]string, len(names))
	var wg sync.WaitGroup
	for i, name := range names {
		wg.Add(1)
		// Since Go 1.22, each iteration has its own i and name, so the goroutine may use them.
		go func() {
			defer wg.Done()
			results[i] = "hello from " + name
		}()
	}
	// Wait returns after every goroutine has returned; their writes are then visible.
	wg.Wait()
	return results
}
greetings_test.go 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

package greetings

import (
	"fmt"
	"slices"
	"testing"
)

func TestThreadGreetings(t *testing.T) {
	var many, manyWant []string
	for i := range 32 {
		many = append(many, fmt.Sprintf("t%d", i))
		manyWant = append(manyWant, fmt.Sprintf("hello from t%d", i))
	}
	cases := []struct {
		name        string
		names, want []string
	}{
		{"two", []string{"Ada", "Linus"}, []string{"hello from Ada", "hello from Linus"}},
		{"three", []string{"main", "worker", "logger"}, []string{"hello from main", "hello from worker", "hello from logger"}},
		{"empty", []string{}, []string{}},
		{"single", []string{"solo"}, []string{"hello from solo"}},
		{"empty-name", []string{""}, []string{"hello from "}},
		{"duplicate", []string{"twin", "twin"}, []string{"hello from twin", "hello from twin"}},
		{"unicode", []string{"Zoë", "李雷"}, []string{"hello from Zoë", "hello from 李雷"}},
		{"many", many, manyWant},
	}
	for _, c := range cases {
		if got := ThreadGreetings(c.names); !slices.Equal(got, c.want) {
			t.Errorf("case %s: got %q, want %q", c.name, got, c.want)
		}
	}
}
greetings.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

//! Starts one thread per name; each thread builds and returns the greeting for its name.

use std::thread;

/// Returns "hello from " + names[i] for each i, each built on its own thread.
/// Panics if the operating system cannot create a thread.
pub fn thread_greetings(names: &[&str]) -> Vec<String> {
    let handles: Vec<thread::JoinHandle<String>> = names
        .iter()
        .map(|name| {
            // spawn needs a 'static closure, so the thread gets its own String, moved in.
            let name = name.to_string();
            thread::spawn(move || format!("hello from {name}"))
        })
        .collect();
    // Start all threads first, then join each one and take its return value.
    handles
        .into_iter()
        .map(|handle| handle.join().expect("a greeter thread panicked"))
        .collect()
}
tests/greetings_test.rs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/start-a-thread/.

use algo_start_a_thread::thread_greetings;

#[test]
fn cases() {
    let cases: Vec<(&str, Vec<&str>, Vec<&str>)> = vec![
        ("two", vec!["Ada", "Linus"], vec!["hello from Ada", "hello from Linus"]),
        ("three", vec!["main", "worker", "logger"], vec!["hello from main", "hello from worker", "hello from logger"]),
        ("empty", vec![], vec![]),
        ("single", vec!["solo"], vec!["hello from solo"]),
        ("empty-name", vec![""], vec!["hello from "]),
        ("duplicate", vec!["twin", "twin"], vec!["hello from twin", "hello from twin"]),
        ("unicode", vec!["Zoë", "李雷"], vec!["hello from Zoë", "hello from 李雷"]),
    ];
    for (name, names, want) in cases {
        assert_eq!(thread_greetings(&names), want, "case {name}");
    }
}

#[test]
fn many() {
    let many: Vec<String> = (0..32).map(|i| format!("t{i}")).collect();
    let names: Vec<&str> = many.iter().map(String::as_str).collect();
    let want: Vec<String> = many.iter().map(|n| format!("hello from {n}")).collect();
    assert_eq!(thread_greetings(&names), want);
}

References

  1. POSIX.1-2024, pthread_create, DESCRIPTION
  2. std::thread, cppreference.com, the class description
  3. Java SE 21 API, java.lang.Thread, the class description; Thread.Builder examples
  4. The Python Standard Library, threading, Thread objects; start(); run()
  5. The Go Programming Language Specification, Go statements; For statements with for clause; Program execution
  6. Go standard library, package sync, type WaitGroup; WaitGroup.Go
  7. The Rust Standard Library, Function std::thread::spawn, the function description
  8. .NET API reference, Thread Class, Remarks (Start a thread; Pass data to a thread)
  9. Node.js documentation, Worker threads, the introduction; new Worker(filename[, options]), the option workerData
  10. std::thread::~thread, cppreference.com, the description

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