c++ - boost scoped_lock。这个会锁吗?

标签 c++ boost concurrency multithreading scoped-lock

已解决

我将 bfs::directory_iterator 队列更改为 std::string 队列,并且令人惊讶地解决了问题。


嗨,我有一种直觉,我做错了。

我已经实现(或尝试)线程池模式。

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 来控制弹出的文件名,如果我推送 2 个文件 (file1) 和 (file2),并使用 2 个线程,我会得到两个“file2”。

  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)));
     }
    }
 };
    

最佳答案

发布的代码看起来没问题 - 如果您发现问题,可能是其他地方应该锁定而不是(例如向队列添加内容的代码)。

关于c++ - boost scoped_lock。这个会锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1468000/

相关文章:

c++ - std::thread 是 boost::thread 的替代品吗?

java - 柜台忙碌等待

c++ - QAbstractListModel dataChanged 信号不更新 ListView (QML)

c++ - 如何减少当前序列化所需的样板

c++ - 打印 3D vector 的所有组合

pipe - 在 C++ 中使用 pipe() 管道管道

c++ - 忽略零权重边的 Boost 图 BFS

c++ - boost 分词器但保留定界符

.net - 并发软件设计

c++ - 这种阻塞队列的实现安全吗?