我改变了BFS :: directory_iterator队列以一个std ::串队列,并且令人惊讶地解决了这个问题。boost scoped_lock。这个锁吗?
嗨,我有一种直觉,认为我做错了事。
我已经实现(或试图)线程池模式。
N个线程从队列中读取,但我遇到了一些麻烦。这是我得到的:
//inside a while loop
bool isEmpty;
bfs::directory_iterator elem;
{
boost::mutex::scoped_lock lock(this->queue_mutex);
isEmpty = this->input_queue.isEmpty();
if (!isEmpty){
elem= *(this->input_queue.pop());
}
else{
continue;
}
}
scoped_lock仍然在if内部工作吗?我开始相信它不会(在运行很多测试之后)。如果没有,是否有任何有限的方式来做到这一点(即不是明确的锁解锁方式)
在此先感谢。
更新
,增加元素到队列中的代码看起来是这样的
//launches the above code, passing a reference to mutex and queue.
Threads threads(queue,queue_mutex);
for (bfs::directory_iterator dir_it:every file in directory){
boost::mutex::scoped_lock lock(queue_mutex);
queue.push(dir_it);
}
林放置COUT来控制POP操作的文件名,并且如果我推2个文件(文件1)和(文件2) ,并使用2个线程,我得到两个“文件2”。
class Threads{
boost::thread::thread_group group;
Thread (N){
//also asigns a reference to a queue and a mutex.
for(i 1..N){
//loop is posted above.
group.add(new boost::thread(boost::bind(&loop,this)));
}
}
};
代码似乎罚款。您的程序以何种方式表现不正确? – avakar 2009-09-23 19:18:28
您发布的代码的确看起来不错。如果你问:“这是否会使用更窄范围的锁(在'if'中)?”,请澄清一下。 – Novelocrat 2009-09-23 19:24:37
锁定真的看起来不错 - 你是否正确地得到了“'file1'”和“'file2'”,如果你像上面那样填充队列,但是读取它是非线程的(即按顺序)? – hjhill 2009-09-23 20:49:01