mardi 3 mars 2015

Static Mutex for Class member Function : C++ 11

Referring to RAII


I can use static mutex for a critical 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?


Aucun commentaire:

Enregistrer un commentaire