Dam*_*mir 6 c++ queue multithreading boost stl
我正在使用队列进行两个线程之间的通信(一个只生成自定义类的实例并将指针推送到队列,另一个从自定义类的队列指针读取并进行一些计算).如何在队列原子上进行推送和弹出,如何锁定那些操作?(我不能使用C++ 11标准)
可移植性最强的非C++ 11锁定机制可能是Boost.Thread库中的同步类型.特别是,mutex类为您提供了一个简单的可锁定对象,用于提供对资源的独占访问.例如:
#include <boost/thread/mutex.hpp>
#include <queue>
template <typename T>
class locking_queue {
public:
void push(T const & value) {
boost::mutex::scoped_lock lock(mutex);
queue.push(value);
}
bool pop(T & value) {
boost::mutex::scoped_lock lock(mutex);
if (queue.empty()) {
return false;
} else {
value = queue.front();
queue.pop();
return true;
}
}
private:
std::queue<T> queue;
boost::mutex mutex;
};
Run Code Online (Sandbox Code Playgroud)
另一个优点是,它与C++ 11 std::mutex类非常相似,如果您决定使用它,这将使转换变得非常简单.
| 归档时间: |
|
| 查看次数: |
1991 次 |
| 最近记录: |