Difference between pointer and reference as thread parameter

The constructor of std::thread deduces argument types and stores copies of them by value. This is needed to ensure the lifetime of the argument object is at least the same as that of the thread. C++ template function argument type deduction mechanism deduces type T from an argument of type T&. All arguments to std::thread … Read more

How to check if a std::thread is still running?

If you are willing to make use of C++11 std::async and std::future for running your tasks, then you can utilize the wait_for function of std::future to check if the thread is still running in a neat way like this: #include <future> #include <thread> #include <chrono> #include <iostream> int main() { using namespace std::chrono_literals; /* Run … Read more

Thread pooling in C++11

This is adapted from my answer to another very similar post. Let’s build a ThreadPool class: class ThreadPool { public: void Start(); void QueueJob(const std::function<void()>& job); void Stop(); void busy(); private: void ThreadLoop(); bool should_terminate = false; // Tells threads to stop looking for jobs std::mutex queue_mutex; // Prevents data races to the job queue … Read more

When should I use std::thread::detach?

In the destructor of std::thread, std::terminate is called if: the thread was not joined (with t.join()) and was not detached either (with t.detach()) Thus, you should always either join or detach a thread before the flows of execution reaches the destructor. When a program terminates (ie, main returns) the remaining detached threads executing in the … Read more

Passing object by reference to std::thread in C++11

Explicitly initialize the thread with a reference_wrapper by using std::ref: auto thread1 = std::thread(SimpleThread, std::ref(a)); (or std::cref instead of std::ref, as appropriate). Per notes from cppreference on std:thread: The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to … Read more

What happens to a detached thread when main() exits?

The answer to the original question “what happens to a detached thread when main() exits” is: It continues running (because the standard doesn’t say it is stopped), and that’s well-defined, as long as it touches neither (automatic|thread_local) variables of other threads nor static objects. This appears to be allowed to allow thread managers as static … Read more