Category : mutex

I recently stumbled upon some behavior that I can’t really understand. Suppose I have an application that creates a named mutex object (we call this the "mutex app"): CreateMutexW(NULL, FALSE, L"MyMutex_{2CFE84A4-FD69-462E-9291-2579BA52B5A1}") and maintains a handle to that throughout the lifetime of the process, for the purposes of not letting other instances of the application run ..

Read more

I know my question is quite similar to this Why does std::lock_guard release the lock after using std::adopt_lock?, but the behavior I see is not. This is my code: #include <mutex> #include <iostream> using namespace std; std::mutex m; void fun2(); void fun1() { cout << "fun1" << endl; std::unique_lock<std::mutex> guard(m); cout << "lock mutex" << ..

Read more

im trying to synchronize a producer consumer case as following (the small reproducible instance of my scenario) #include<thread> #include<condition_variable> #include<deque> class Multi_Thread_Test{ public: std::mutex mu; std::condition_variable cond; std::deque<int>stored; Multi_Thread_Test(){ } void Producer(){ std::unique_lock<std::mutex>locker(mu); srand(time(0)); stored.push_back(rand()); locker.unlock(); cond.notify_one(); } void Producer_loop(){ while(true){ std::thread t1([&]{Producer();}); std::thread t2([&]{Producer();}); t1.join(); t2.join(); std::this_thread::sleep_for(std::chrono::seconds(5)); } } void Consumer() { std::thread pl([&]{this->Producer_loop();}); ..

Read more

I’m writing a program where there are two threads, the first thread scans an input file(one int per line) and assigns the number to a global variable. The second thread then reads the global variable and if it’s even prints it twice to a file and if odd prints it only once. For example if ..

Read more

I am reading C++ concurrency in action. It says that when you use std::execution::par, you can use mutex per internal element like below. #include <mutex> #include <vector> class X { mutable std::mutex m; int data; public: X() : data(0) {} int get_value() const { std::lock_guard guard(m); return data; } void increment() { std::lock_guard guard(m); ++data; ..

Read more