Skip to content
C++

Multithreading

thread, mutex, condition_variable.

By EZ4Code Team
threadmultithreading

Code

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <vector>

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void worker(int id) {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [] { return ready; });
    std::cout << "Thread " << id << " working\n";
}

int main() {
    // Create thread
    std::vector<std::thread> threads;
    for (int i = 0; i < 5; ++i)
        threads.emplace_back(worker, i);

    // Notify all threads
    {
        std::lock_guard<std::mutex> lock(mtx);
        ready = true;
    }
    cv.notify_all();

    for (auto& t : threads) t.join();

    // async and future
    auto future = std::async(std::launch::async, []() {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        return 42;
    });
    std::cout << "Result: " << future.get() << "\n";

    // promise
    std::promise<int> promise;
    auto fut = promise.get_future();
    std::thread([&promise]() {
        promise.set_value(100);
    }).join();
    std::cout << "Promise: " << fut.get() << "\n";

    return 0;
}

Explanation

thread creates threads; mutex protects shared data; condition_variable synchronizes; async/promise gets async results.

More C++ Snippets