About thread-safety of weak_ptr

I know I’m late, but this comes up when searching for “weak_ptr thread”, and Casey’s answer just isn’t the whole truth. Both shared_ptr and weak_ptr can be used from threads without further synchronization. For shared_ptr, there’s a lot of documentation (e.g. on cppreference.com or on stackoverflow). You can safely access shared_ptr‘s that point to the … Read more

Write concurrently vector

Concurrent writes to vector<bool> are never ok, because the underlying implementation relies on a proxy object of type vector<bool>::reference which acts as if it was a reference to bool, but in reality will fetch and update the bitfield bytes as needed. When using multiple threads without synchronization, the following might happen: Thread 1 is supposed … Read more

std::thread calling method of class [duplicate]

Not so hard: #include <thread> void Test::runMultiThread() { std::thread t1(&Test::calculate, this, 0, 10); std::thread t2(&Test::calculate, this, 11, 20); t1.join(); t2.join(); } If the result of the computation is still needed, use a future instead: #include <future> void Test::runMultiThread() { auto f1 = std::async(&Test::calculate, this, 0, 10); auto f2 = std::async(&Test::calculate, this, 11, 20); auto res1 … Read more