Yep: 增强线程 http://www.boost.org/doc/html/thread.html很棒,应该非常适合您的需求。 (现在,很多人说你几乎可以将 Boost 视为内置功能。)
仍然没有可以开箱即用的类,但是一旦您手头有了同步原语,实现您自己的线程安全包装器确实非常简单,例如,std::stack
。它可能看起来像这样(没有实现每个方法......):
template <typename T> class MyThreadSafeStack {
public:
void push(const T& item) {
boost::mutex::scoped_lock lock(m_mutex);
m_stack.push(item);
}
void pop() {
boost::mutex::scoped_lock lock(m_mutex);
m_stack.pop();
}
T top() const { // note that we shouldn't return a reference,
// because another thread might pop() this
// object in the meanwhile
boost::mutex::scoped_lock lock(m_mutex);
return m_stack.top();
}
private:
mutable boost::mutex m_mutex;
std::stack<T> m_stack;
}
如果您是 C++ 新手,请了解RAII http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization。与这种情况相关的是,Boost.Thread 有“作用域锁”类,这样就很难因为忘记释放锁而搬起石头砸自己的腿。
如果您发现自己编写了这样的代码:
void doStuff() {
myLock.lock();
if (!condition) {
reportError();
myLock.unlock();
return;
}
try {
doStuffThatMayThrow();
}
catch (std::exception& e) {
myLock.unlock();
throw e;
}
doMoreStuff();
myLock.unlock();
}
,那么你应该直接说“不”,然后转而使用 RAII(语法不是直接来自 Boost):
void doStuff() {
scoped_lock lock;
if (!condition) {
reportError();
return;
}
doStuffThatMayThrow();
doMoreStuff();
}
关键是当scoped_lock
对象超出范围,它的析构函数释放资源——在本例中是锁。无论您是通过抛出异常还是通过执行奇数退出作用域,这种情况总是会发生return
您的同事在函数中间偷偷添加的语句,或者只是到达函数末尾。