正确处理std :: stack的正确方法

时间:2017-11-23 20:34:44

标签: c++ multithreading c++11 thread-synchronization

这可能是多线程编程方面的基本问题,但我真的希望在没有任何并发​​数据结构的情况下实现以下目标。 考虑一下代码:

class A
{
    std::stack<int> s;
public:
    A()
    {
        s.push(7); s.push(6); s.push(5); s.push(4); s.push(3); s.push(2); s.push(1);
    }
    void process(int tid)
    {
        while (!s.empty())
        {
            std::unique_lock<std::mutex> lck(m);
            std::cout << tid << " --> " << s.top() << '\n';
            cv.wait(lck);
            s.pop();
            cv.notify_all();
            lck.unlock();
        }
    }
    std::mutex m;
    std::condition_variable cv;
};

int main()
{   
    A a;
    std::thread t1(&A::process, &a, 1);
    std::thread t2(&A::process, &a, 2);    
    t1.join();
    t2.join();
}

我希望每个线程都能打印堆栈顶部并将其弹出,以便输出看起来像这样:

1 --> 1
2 --> 2
1 --> 3
2 --> 4
...

因此只有1个线程应该进入while主体并且只执行一次迭代。

但它始终输出:

1 --> 1
2 --> 1 

然后它无限地等待

我该怎么做?

目前的解决方案有什么问题?

1 个答案:

答案 0 :(得分:1)

永远不要在没有测试虚假唤醒的情况下对条件变量进行wait。最简单的方法是使用lambda verson。

condition_variable不是信号量,它们的级别低于信号量。

class A
{
public:
  A()
  {
    s.push(7); s.push(6); s.push(5); s.push(4); s.push(3); s.push(2); s.push(1);
  }
  void process(int tid)
  {
    while (true)
    {
      std::unique_lock<std::mutex> lck(m);
      cv.wait(lck, [&]{ return std::this_thread::get_id() != last || s.empty(); });
      // must only read within lock:
      if (s.empty()) {
        last = std::thread::id{}; // thread ids can be reused
        break;
      }
      last = std::this_thread::get_id();
      std::cout << tid << " --> " << s.top() << '\n';
      s.pop();
      cv.notify_one();
    }
  }
  std::mutex m;
  std::condition_variable cv;
  std::thread::id last{};
  std::stack<int> s;
};