引用RAII
我可以将 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;
};
哪种方式保证线程安全比较好?
最佳答案
“在成员函数中声明的静态变量将在函数调用之间保留它们的值。所有实例将只有一个副本”
你的两个解决方案都是“有效的”,这实际上取决于你想要完成什么......
成员函数内部的静态互斥变量
此解决方案为该类的所有实例提供了一个互斥体。它将有效地提供线程安全,但如果您有许多对象分布在不同的线程中,则可能不是最佳性能。 互斥量也仅限于那个单一的功能,所以通常这使得实现不切实际。因此,静态私有(private)变量通常更好。
类内部的私有(private)互斥变量
使用此解决方案,您可以为类的每个实例获得一个互斥锁。为您的类提供线程安全性以便多个线程可以访问它会很有效。这通常是更受欢迎的解决方案,因为它允许不同的线程同时访问不同的对象。 但是,这不足以保护对您类的静态成员的访问。
大多数时候你希望在你的类中有一个私有(private)的非静态互斥量。
关于multithreading - 类成员函数的静态互斥体 : C++ 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28827830/