我可以使用static mutex
用於critical section
爲:
#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)
}
如果使用同樣的方法一類的成員函數,例如:
class Test{
public:
void setI(int k)
{
static std::mutex mutex;
std::lock_guard<std::mutex> lock(mutex);
i=k;
}
private:
int i;
};
以上方法的缺點和優點是什麼?
是更可取的使用方法如下:
class Test
{
public:
void setI(int k)
{
std::lock_guard<std::mutex> lock(mutex);
i = k;
}
private:
int i;
std::mutex mutex;
};
何種方法來保證線程安全是更好?
你正試圖用這些解決方案解決什麼問題? – 2015-03-03 09:12:58