是的:Boost.Thread很棒,应该非常适合您的需求。(现在,很多人说您几乎可以将 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。与这种情况相关,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
您的同事在函数中间偷偷添加的奇怪语句,或者只是通过到达函数末尾,这种情况总是会发生。