Goroutines in C++

Our example demonstrates the use of lightweight execution threads called goroutines. Here’s the full source code translated into C++ using threads.

#include <iostream>
#include <thread>
#include <chrono>

// Define a function that prints a message along with a counter
void f(const std::string& from) {
    for (int i = 0; i < 3; ++i) {
        std::cout << from << " : " << i << std::endl;
    }
}

int main() {
    // Call the function synchronously
    f("direct");

    // Spawn a new thread to run the function concurrently
    std::thread t1(f, "thread");

    // Spawn another thread to run an anonymous function
    std::thread t2([](const std::string& msg) {
        std::cout << msg << std::endl;
    }, "going");

    // Wait for the threads to finish
    t1.join();
    t2.join();

    // Pause the main thread to ensure all threads complete before exiting
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "done" << std::endl;

    return 0;
}

To compile and run this program, use the following commands:

$ g++ -std=c++11 -o goroutines goroutines.cpp
$ ./goroutines
direct : 0
direct : 1
direct : 2
thread : 0
going
thread : 1
thread : 2
done

In this program, we see the output of the synchronous call first, followed by the output from the concurrent threads. The output from the threads may be interleaved since they are running concurrently.

Next, we’ll look at a complement to threads in concurrent C++ programs: futures and async tasks.