【发布时间】:2014-04-19 20:21:13
【问题描述】:
我正在寻找一种锁,它允许在 GUI 和后端之间进行线程安全的转换。
只是为了双倍,但我相信它最终会被用于其他事情。
现在这是我不确定的部分,在现代 CPU 上,是否可以同时读取和写入导致竞争条件?还是只有当两个线程同时尝试写入时。
我总是将与线程交叉的所有变量都封装在一个模板对象中,这允许我同样使用但需要锁定,这里是基础:
//=====================================================================================================
// Class to store a variable in a thread safe manner.
//=====================================================================================================
template <class T>
class ThreadSafeVariable
{
public:
ThreadSafeVariable(const T & variable):
_stored_variable(variable)
{
}
ThreadSafeVariable():
_stored_variable()
{
}
//=====================================================================================================
/// Returns the stored variable
//=====================================================================================================
T Read() const
{
boost::unique_lock<boost::mutex> lock(_mutex);
return _stored_variable;
}
//=====================================================================================================
/// Sets the variable
//=====================================================================================================
void operator = (const T &value_to_set)
{
boost::unique_lock<boost::mutex> lock(_mutex);
_stored_variable = value_to_set;
}
//=====================================================================================================
/// Returns the stored variable
//=====================================================================================================
operator T() const
{
boost::unique_lock<boost::mutex> lock(_mutex);
return (T) _stored_variable;
}
void SetFromString (const std::string & value_to_set);
T operator ++ (int);
T operator -- (int);
std::string ToString() const;
protected:
T _stored_variable;
mutable boost::mutex _mutex;
};
如果只有一个线程可以选择写入(该部分需要通过调用不同的函数进行编码),是否有可能使这样的类更快。
基本上我有一个静态函数,我想保持静态,它会根据我想在 GUI 上更改的参数而变化,但它是软件的性能关键部分。
我知道自旋锁,原子。但从未真正使用过它们。我猜自旋锁会浪费 CPU,而且我不确定原子能带来的性能提升。
【问题讨论】:
-
您是不是真的要使用read/write lock 之类的东西?
-
您可能也想探索“自旋锁”。
标签: c++ c multithreading thread-safety