Sobes.tech
Junior — Senior

Display of identifiers and counters from different threads

livecode

Task condition

Describe and analyze the behavior of the following program that uses the C++ standard library to create and manage threads.

void worker() {
    constexpr uint8_t SIZE = 10u;
    for (uint8_t i = 0u; i < SIZE; ++i) {
        std::cout << std::this_thread::get_id() << " => " << i << std::endl;
    }
}
int main(int argc, char** argv) {
    std::thread t1(worker);
    std::thread t2(worker);
    if (t1.joinable()) {
        t1.join();
    }
    if (t2.joinable()) {
        t2.join();
    }
    return EXIT_SUCCESS;
}

In your explanation, describe how the output from the two concurrently running threads occurs, why joinable() and join() are used, and what influence the thread scheduler might have on the order of printing.