~/okanakyuz
← all posts

Threads in C++

Notes on std::thread in C++: join and detach, passing arguments with std::ref and std::cref, and protecting shared data with a mutex.

15 March 2020updated 25 November 20262 min read

Threads running in parallel

In C++ you can run code concurrently by using threads. std::thread is in the <thread> header and has been part of the standard since C++11.

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

void myThread(){
    std::cout << "thread runs : " << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(4));
    std::cout << "Thread ends" << std::endl;
}

int main()
{
    std::thread th(myThread);
    std::cout << "Normal routine" << std::endl;

    // join makes the main thread wait until the child thread ends.
    th.join();
}

The join method makes the main thread wait for the child. detach cuts the connection between the main thread and the child thread, so the child keeps running on its own. Keep in mind that a std::thread which is still joinable when it is destroyed calls std::terminate, so you must call either join or detach before it goes out of scope.

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

void myThread(){
    std::cout << "thread runs : " << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(4));
    std::cout << "Thread ends" << std::endl;
}

int main()
{
    std::thread th(myThread);
    // main thread will not wait
    th.detach();
    std::cout << "Normal routine" << std::endl;

    // if the child thread is joinable, join it
    // but it is detached, so joinable() returns false
    if(th.joinable())
        th.join(); // this line won't run

    // give the detached thread time to finish before main returns
    std::this_thread::sleep_for(std::chrono::seconds(10));
}

The sleep at the end is only there for the demo. When main returns, the process ends and a detached thread is killed wherever it is, so in real code you need a proper way to know that the detached work is done.

Passing arguments

You can also pass arguments to the thread. Just add them after the function in the std::thread constructor.

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

class SimpleClass{
public:
    SimpleClass(){
        std::cout << "SimpleClass()" << std::endl;
    }
    SimpleClass(const SimpleClass &s){
        std::cout << "SimpleClass(const SimpleClass &s)" << std::endl;
    }
    SimpleClass(SimpleClass && s){
        std::cout << "SimpleClass(SimpleClass && s)" << std::endl;
    }
    ~SimpleClass(){
        std::cout << "~SimpleClass()" << std::endl;
    }
};

void myThread(SimpleClass s){
    std::cout << "thread runs : " << std::this_thread::get_id() << std::endl;
}

int main()
{
    SimpleClass s{};
    std::thread th(myThread, s);
    th.join();
    std::cout << "Program ends" << std::endl;
}

But this creates extra objects. std::thread first copies s into its own storage, and then that copy is moved into the parameter of myThread. If you change the parameter to a reference, SimpleClass &s, the code above does not even compile, because the thread always stores its arguments by value. You could pass a pointer, but the cleaner way is the helper std::ref from <functional>:

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

class SimpleClass{
public:
    SimpleClass(){
        std::cout << "SimpleClass()" << std::endl;
    }
    SimpleClass(const SimpleClass &s){
        std::cout << "SimpleClass(const SimpleClass &s)" << std::endl;
    }
    SimpleClass(SimpleClass && s){
        std::cout << "SimpleClass(SimpleClass && s)" << std::endl;
    }
    ~SimpleClass(){
        std::cout << "~SimpleClass()" << std::endl;
    }
};

void myThread(SimpleClass &s){
    std::cout << "thread runs : " << std::this_thread::get_id() << std::endl;
}

int main()
{
    SimpleClass s{};
    std::thread th(myThread, std::ref(s));
    th.join();
    std::cout << "Program ends" << std::endl;
}

With a reference (or a pointer) you are responsible for the lifetime: s must stay alive until the thread is done with it. Here join guarantees that.

On the other hand, you may use std::cref for constant references:

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

class SimpleClass{
public:
    SimpleClass(){
        std::cout << "SimpleClass()" << std::endl;
    }
    SimpleClass(const SimpleClass &s){
        std::cout << "SimpleClass(const SimpleClass &s)" << std::endl;
    }
    SimpleClass(SimpleClass && s){
        std::cout << "SimpleClass(SimpleClass && s)" << std::endl;
    }
    ~SimpleClass(){
        std::cout << "~SimpleClass()" << std::endl;
    }
};

void myThread(const SimpleClass &s){
    std::cout << "thread runs : " << std::this_thread::get_id() << std::endl;
}

int main()
{
    SimpleClass s{};
    std::thread th(myThread, std::cref(s));
    th.join();
    std::cout << "Program ends" << std::endl;
}

Using the same variables with a mutex

If multiple threads use the same variable and at least one of them writes to it, you have to protect it, otherwise you have a data race, which is undefined behavior. The simplest tool is a mutex. A mutex has two important methods: lock and unlock.

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

int main()
{
    // create a mutex
    std::mutex m_mutex{};
    int i{0};
    auto fn = [&i, &m_mutex](int x){
        for(int j = 0; j < x; j++){
            // lock that mutex
            m_mutex.lock();
            i++;
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
            std::cout << std::this_thread::get_id() << " -- " << i << std::endl;
            m_mutex.unlock();
        }
    };

    std::thread th1(fn, 10);
    std::thread th2(fn, 10);
    th1.join();
    th2.join();
}

Calling lock and unlock by hand works, but if something throws between them the mutex stays locked forever. In practice I use std::lock_guard instead, which unlocks in its destructor:

for(int j = 0; j < x; j++){
    std::lock_guard<std::mutex> guard(m_mutex);
    i++;
    std::cout << std::this_thread::get_id() << " -- " << i << std::endl;
} // unlocked here

Update (2026): C++20 added std::jthread. It joins automatically in its destructor, so you can’t forget the join, and it supports cooperative cancellation with std::stop_token. If the function takes a std::stop_token as its first parameter, the jthread passes one in, and the destructor calls request_stop() before joining.

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

int main()
{
    std::jthread th([](std::stop_token st){
        while(!st.stop_requested()){
            std::cout << "working..." << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }
    });
    std::this_thread::sleep_for(std::chrono::seconds(2));
} // th.request_stop() and th.join() are called here