【发布时间】:2014-05-14 17:55:29
【问题描述】:
有时BlockingQueue 的这种实现和执行可以正常工作。有时它会出现段错误。知道为什么吗?
#include <thread>
using std::thread;
#include <mutex>
using std::mutex;
#include <iostream>
using std::cout;
using std::endl;
#include <queue>
using std::queue;
#include <string>
using std::string;
using std::to_string;
#include <functional>
using std::ref;
template <typename T>
class BlockingQueue {
private:
mutex mutex_;
queue<T> queue_;
public:
T pop() {
this->mutex_.lock();
T value = this->queue_.front();
this->queue_.pop();
this->mutex_.unlock();
return value;
}
void push(T value) {
this->mutex_.lock();
this->queue_.push(value);
this->mutex_.unlock();
}
bool empty() {
this->mutex_.lock();
bool check = this->queue_.empty();
this->mutex_.unlock();
return check;
}
};
void fillWorkQueue(BlockingQueue<string>& workQueue) {
int size = 40000;
for(int i = 0; i < size; i++)
workQueue.push(to_string(i));
}
void doWork(BlockingQueue<string>& workQueue) {
while(!workQueue.empty()) {
workQueue.pop();
}
}
void multiThreaded() {
BlockingQueue<string> workQueue;
fillWorkQueue(workQueue);
thread t1(doWork, ref(workQueue));
thread t2(doWork, ref(workQueue));
t1.join();
t2.join();
cout << "done\n";
}
int main() {
cout << endl;
// Multi Threaded
cout << "multiThreaded\n";
multiThreaded();
cout << endl;
}
【问题讨论】:
-
如果出现段错误,我想你可以得到它发生的代码行?了解一下可能会有所帮助...
-
如果你检查
itemQueue是否为空,然后让其他线程做一些工作,然后pop()一个项目会发生什么? -
这个问题有足够的代码,任何人都可以尝试一下,自己看看问题出在哪里。也没有太多多余的代码,所以离教科书SSCCE不远了,当然可以回答。
-
@Flexo 我很难相信“这个程序的错误在哪里?”可能是个好问题。
标签: c++ multithreading c++11 blockingqueue