Static Mutex for Class member Function : C++ 11
"Static variables declared in member functions will keep their value between function calls. There will be only one copy over all instances"
Both of your solutions is "valid", it really depends on what you want to accomplish...
static mutex variable inside member function
This solution gives you one mutex for all instances of the class. It will be effective in providing thread-safety but might not be optimal for performance if you have many objects you spread across different threads. The mutex is also limited to only that single function so usually this makes the implementation impractical. A static private variable is usually better therefore.
private mutex variable inside class
With this solution you get one mutex per instance of your class. It will be effective to provide thread safety for your class so that multiple threads can access it. This is usually the more preferred solution as it allows different threads to access different objects at the same time. However this will not be sufficient to protect access to static members of your class.
Most of the time you want to have a private non-static mutex inside your class.
Gaurav K
Masters Engineering Embedded Software University Of Glasgow : 2011-2012
Updated on June 05, 2022Comments
-
Gaurav K almost 2 years
Referring to RAII
I can use
static mutex
for acritical section
as:#include <string> #include <mutex> #include <iostream> #include <fstream> #include <stdexcept> void write_to_file (const std::string & message) { // mutex to protect file access static std::mutex mutex; // lock mutex before accessing file std::lock_guard<std::mutex> lock(mutex); // try to open file std::ofstream file("example.txt"); if (!file.is_open()) throw std::runtime_error("unable to open file"); // write message to file file << message << std::endl; // file will be closed 1st when leaving scope (regardless of exception) // mutex will be unlocked 2nd (from lock destructor) when leaving // scope (regardless of exception) }
If use the same approach for a class member function such as:
class Test{ public: void setI(int k) { static std::mutex mutex; std::lock_guard<std::mutex> lock(mutex); i=k; } private: int i; };
What are the cons and pros of above approach?
Is it more advisable to use the approach as below:
class Test { public: void setI(int k) { std::lock_guard<std::mutex> lock(mutex); i = k; } private: int i; std::mutex mutex; };
which method to ensure thread safety is better?