Massive CPU load using std::lock (c++11)

On my machine, the following code prints out 10 times a second and consumes almost 0 cpu because most of the time the thread is either sleeping or blocked on a locked mutex: #include <chrono> #include <thread> #include <mutex> #include <iostream> using namespace std::chrono_literals; std::mutex m1; std::mutex m2; void f1() { while (true) { std::unique_lock<std::mutex> … Read more

C++11: What happens if you don’t call join() for std::thread

If you have not detached or joined a thread when the destructor is called it will call std::terminate, we can see this by going to the draft C++11 standard we see that section 30.3.1.3 thread destructor says: If joinable(), calls std::terminate(). Otherwise, has no effects. [ Note: Either implicitly detaching or joining a joinable() thread … Read more

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

Confusion about threads launched by std::async with std::launch::async parameter

The std::async (part of the <future> header) function template is used to start a (possibly) asynchronous task. It returns a std::future object, which will eventually hold the return value of std::async‘s parameter function. When the value is needed, we call get() on the std::future instance; this blocks the thread until the future is ready and … Read more

C++11: std::thread pooled?

Generally, std::thread should be a minimal wrapper around underlying system primitive. For example, if you’re on pthread platform, you can test with the following program that no matter how many threads you create, they are all created with unique pthread_t ids (which implies they’re created on the fly and not borrowed from a thread pool): … 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