Channel Synchronization in C++

The following example demonstrates how to use channels for synchronization between threads. In C++, we’ll use std::thread for concurrency and std::condition_variable for synchronization.

#include <iostream>
#include <thread>
#include <chrono>
#include <condition_variable>
#include <mutex>

// This is the function we'll run in a separate thread. The
// done flag and condition variable will be used to notify the
// main thread that this function's work is done.
void worker(bool& done, std::condition_variable& cv, std::mutex& mutex) {
    std::cout << "working...";
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "done" << std::endl;

    // Notify that we're done
    {
        std::lock_guard<std::mutex> lock(mutex);
        done = true;
    }
    cv.notify_one();
}

int main() {
    bool done = false;
    std::condition_variable cv;
    std::mutex mutex;

    // Start a worker thread, giving it the flag and condition variable to notify on
    std::thread worker_thread(worker, std::ref(done), std::ref(cv), std::ref(mutex));

    // Block until we receive a notification from the worker thread
    {
        std::unique_lock<std::mutex> lock(mutex);
        cv.wait(lock, [&done] { return done; });
    }

    worker_thread.join();

    return 0;
}

To compile and run this program:

$ g++ -std=c++11 -pthread channel_synchronization.cpp -o channel_synchronization
$ ./channel_synchronization
working...done

In this C++ version, we use a std::thread to run the worker function concurrently. Instead of channels, we use a boolean flag done, a std::condition_variable, and a std::mutex for synchronization.

The worker function simulates work by sleeping for a second, then sets the done flag and notifies the condition variable.

In the main function, we start the worker thread and then wait on the condition variable until the done flag is set. This blocks the main thread until the worker thread completes its task.

If you removed the waiting code in the main function, the program might exit before the worker thread even started or completed its work.

This approach demonstrates thread synchronization in C++, which is conceptually similar to channel synchronization in other languages, but uses different mechanisms that are idiomatic to C++.