Posts

Showing posts with the label multithreading

Why would concurrency using std::async be faster than using std::thread?

23 1 I was reading Chapter 8 of the "Modern C++ Programming Cookbook, 2nd edition" on concurrency and stumbled upon something that puzzles me. The author implements different versions of parallel map and reduce functions using std::thread and std::async . The implementations are really close; for example, the heart of the parallel_map functions are // parallel_map using std::async ... tasks.emplace_back(std::async( std::launch::async, [=, &f] {std::transform(begin, last, begin, std::forward<F>(f)); })); ... // parallel_map using std::thread ... threads.emplace_back([=, &f] {std::transform(begin, last, begin, std::forward<F>(f)); }); ... The complete code can be found here for std::thread and there for std::async . What puzzles m...

Two threads executing synchronized block simultaneously

Below is the code where a Thread enters a synchronized block, waits for 5seconds and then exits. I have started two Thread instances simultaneously. The expectation was one of the threads will own the lock on the synchronized object & the other will wait. After 5 seconds, when the lock owner exits, the waiting thread will execute. But, in actual, both the threads are executing the synchronized block simultaneously and also exiting at the same time. Expected Output: Thread-X <timeX> received the lock. Thread-X <timeX+5s> exiting... Thread-Y <timeY> received the lock. Thread-Y <timeY+5s> exiting... Actual Output: Thread-X <time> received the lock. Thread-Y <time> received the lock. Thread-X <time+5s> exiting... Thread-Y <time+5s> exiting... Any explanation of the above behavior will be really helpful. Am I missing something here? import java.text.SimpleDateFormat; import java.util.Date; public class Test2 { public static void main(S...

Try catch with locks in C++

In Java: Lock lock = new ReentrantLock(); try{ lock.lock(); someFunctionLikelyToCauseAnException(); } catch(e){...} finally { lock.unlock(); } My question is with this above example we know that the lock WILL always get unlocked because finally always executes, but what is the guarantee with C++? mutex m; m.lock(); someFunctionLikelyToCauseAnException(); /// ???? How will this work and why? For this we use the RAII-style construct std::lock_guard. When you use std::mutex m; { // start of some scope std::lock_guard lg(m); // stuff } // end of scope lg will ensure that m will be unlocked no matter what path the scope is left as it is destroyed at scope exit and std::lock_guards destructor will call unlock Even if an exception is thrown the stack will be unwound (stack unwinding) and that process destroys lg which in turn will call unlock guaranteeing that the lock is released. what is the guarantee with C++? The relevant guarantee in C++ works a bit differently...