LearnFrenzy
Sign in Take a free test

Multithreading · Exercise 2 of 4

Multithreading Predict the Output

  • 20 questions
  • Page 2 of 2
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

Read each C++ program and choose what it prints. Every program is free of data races and prints the same result on every run.

Question 11 Medium

What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)

main.cpp
#include <iostream>
#include <thread>
#include <vector>

int main() {
    std::vector<long> sums(3);
    {
        std::vector<std::jthread> workers;
        for (int i = 0; i < 3; ++i)
            workers.emplace_back([&sums, i] { for (int k = 1; k <= 100 * (i + 1); ++k) sums[i] += k; });
    }   // all jthreads are joined here – no explicit join, no terminate
    std::cout << sums[0] << ' ' << sums[1] << ' ' << sums[2] << '\n';
    return 0;
}
A 5050 20100 45150
B 5050 5050 5050
C 0 0 0
D The program terminates
Question page & discussion
Question 12 Hard

What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)

main.cpp
#include <atomic>
#include <iostream>
#include <thread>

int main() {
    std::atomic<int> processed{0};
    std::atomic<bool> started{false};
    std::jthread worker([&](std::stop_token st) {
        started = true;
        while (!st.stop_requested()) processed.fetch_add(1);
    });
    while (!started) {}                      // wait until the worker is running
    worker.request_stop();
    worker.join();
    std::cout << worker.get_stop_token().stop_requested() << ' ' << (processed >= 0) << ' ' << worker.joinable() << '\n';
    return 0;
}
A 1 1 0
B 0 1 1
C 1 0 0
D The program never ends
Question page & discussion
Question 13 Medium

What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)

main.cpp
#include <iostream>
#include <latch>
#include <thread>
#include <vector>

int main() {
    const int n = 4;
    std::vector<int> loaded(n, 0);
    std::latch done(n);
    std::vector<std::jthread> pool;
    for (int i = 0; i < n; ++i)
        pool.emplace_back([&, i] {
            loaded[i] = (i + 1) * 100;
            done.count_down();               // "I am finished"
        });
    done.wait();                             // blocks until the count reaches zero
    int total = 0;
    for (int v : loaded) total += v;         // safe: every worker has counted down after writing
    std::cout << total << ' ' << done.try_wait() << '\n';
    return 0;
}
A 1000 1
B 1000 0
C 0 1
D 400 1
Question page & discussion
Question 14 Hard

What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)

main.cpp
#include <barrier>
#include <iostream>
#include <thread>
#include <vector>

int main() {
    const int n = 3;
    std::vector<int> a(n), b(n);
    int phases = 0;
    std::barrier sync(n, [&]() noexcept { ++phases; });   // completion step: runs once per phase
    std::vector<std::jthread> pool;
    for (int i = 0; i < n; ++i)
        pool.emplace_back([&, i] {
            a[i] = i + 1;                    // phase 1
            sync.arrive_and_wait();
            b[i] = a[0] + a[1] + a[2];       // phase 2 reads everyone's phase-1 result
            sync.arrive_and_wait();
        });
    pool.clear();
    std::cout << b[0] << b[1] << b[2] << ' ' << phases << '\n';
    return 0;
}
A 666 2
B 123 2
C 666 1
D 666 6
Question page & discussion
Question 15 Hard

What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)

main.cpp
#include <atomic>
#include <chrono>
#include <iostream>
#include <semaphore>
#include <thread>
#include <vector>

int main() {
    std::counting_semaphore<3> slots(3);       // at most 3 at a time
    std::atomic<int> inside{0}, peak{0}, finished{0};
    std::vector<std::jthread> pool;
    for (int i = 0; i < 10; ++i)
        pool.emplace_back([&] {
            slots.acquire();
            int now = ++inside;
            int p = peak.load();
            while (now > p && !peak.compare_exchange_weak(p, now)) {}
            std::this_thread::sleep_for(std::chrono::milliseconds(2));
            --inside;
            ++finished;
            slots.release();
        });
    pool.clear();
    std::cout << finished << ' ' << (peak <= 3) << ' ' << inside << '\n';
    return 0;
}
A 10 1 0
B 10 0 0
C 3 1 0
D 10 1 3
Question page & discussion
Question 16 Medium

What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)

main.cpp
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

struct Wallet { std::mutex m; int coins; };

void move_coins(Wallet& from, Wallet& to, int n) {
    std::scoped_lock lock(from.m, to.m);
    if (from.coins >= n) { from.coins -= n; to.coins += n; }
}

int main() {
    Wallet w[3] = {{{}, 100}, {{}, 100}, {{}, 100}};
    std::vector<std::thread> pool;
    for (int t = 0; t < 3; ++t)
        pool.emplace_back([&w, t] { for (int i = 0; i < 1000; ++i) move_coins(w[t], w[(t + 1) % 3], 1); });
    for (auto& th : pool) th.join();
    std::cout << w[0].coins + w[1].coins + w[2].coins << '\n';
    return 0;
}
A 300
B It varies between runs
C 0
D 3000
Question page & discussion
Question 17 Hard

What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)

main.cpp
#include <future>
#include <iostream>
#include <string>
#include <thread>

int main() {
    std::packaged_task<std::string(std::string, int)> task([](std::string s, int n) {
        std::string out;
        for (int i = 0; i < n; ++i) out += s;
        return out;
    });
    std::future<std::string> result = task.get_future();
    std::thread t(std::move(task), "ab", 3);     // the task is move-only
    std::cout << result.get() << ' ' << result.valid() << '\n';
    t.join();
    return 0;
}
A ababab 0
B ababab 1
C ab 0
D Compilation error
Question page & discussion
Question 18 Medium

What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)

main.cpp
#include <iostream>
#include <mutex>

int main() {
    std::mutex m;
    std::unique_lock<std::mutex> lock(m, std::defer_lock);   // associated, but not locked yet
    std::cout << lock.owns_lock();
    lock.lock();
    std::cout << lock.owns_lock();
    lock.unlock();                                           // unlock early…
    std::cout << lock.owns_lock();
    std::unique_lock<std::mutex> other(m, std::try_to_lock);
    std::cout << other.owns_lock() << '\n';                  // …so another lock can take it
    return 0;
}
A 0101
B 1101
C 0100
D 1111
Question page & discussion
Question 19 Hard

What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)

main.cpp
#include <iostream>
#include <map>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <thread>
#include <vector>

class PriceTable {
    mutable std::shared_mutex m_;
    std::map<std::string, int> prices_{{"pen", 20}, {"ink", 45}};
public:
    int get(const std::string& k) const { std::shared_lock lock(m_); return prices_.at(k); }
    void raise(const std::string& k, int by) { std::unique_lock lock(m_); prices_[k] += by; }
};

int main() {
    PriceTable t;
    std::vector<long> read_sum(4, 0);
    std::vector<std::thread> pool;
    pool.emplace_back([&t] { for (int i = 0; i < 10; ++i) t.raise("pen", 1); });
    for (int r = 0; r < 3; ++r)
        pool.emplace_back([&t, &read_sum, r] { for (int i = 0; i < 100; ++i) read_sum[r] += t.get("ink"); });
    for (auto& th : pool) th.join();
    std::cout << t.get("pen") << ' ' << read_sum[0] << ' ' << read_sum[1] << ' ' << read_sum[2] << '\n';
    return 0;
}
A 30 4500 4500 4500
B 20 4500 4500 4500
C 30 450 450 450
D It varies between runs
Question page & discussion
Question 20 Medium

What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)

main.cpp
#include <iostream>
#include <thread>
#include <utility>

int main() {
    std::thread a([] {});
    std::thread b([] {});
    std::thread c;                          // default-constructed: no thread
    std::cout << a.joinable() << b.joinable() << c.joinable() << ' ';
    c = std::move(b);                       // ownership of the thread moves to c
    std::cout << b.joinable() << c.joinable() << ' ';
    a.join();
    c.join();
    std::cout << a.joinable() << c.joinable() << '\n';
    return 0;
}
A 110 01 00
B 111 01 00
C 110 11 00
D 110 01 11
Question page & discussion
Up next · Exercise 3Find the Error10 questions

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links