1

我想实现一种机制,允许我阻止程序流,直到异步操作完成。(主要用于没有消息循环的单元测试。)

我创建的代码创建了一个线程并等待线程内的条件通知:

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <thread>

struct Blocker {
    Blocker() :
        wait_thread([this]() {
            std::mutex mtx;
            std::unique_lock<std::mutex> lck(mtx);            
            cond.wait(lck);
        })
    {
    }

    void wait() { wait_thread.join(); }

    void notify() { cond.notify_one(); }

    std::condition_variable cond;    
    std::thread wait_thread;
};

template<typename Callback>
void async_operation(const Callback & cb) { cb(); }

int main() {
    Blocker b;
    async_operation([&](){ b.notify(); });
    b.wait();
}

问题是它经常死锁,因为调用notify发生在线程甚至开始之前。我应该如何解决这个问题?

4

1 回答 1

2
#include <mutex>
#include <condition_variable>

struct blocker
{
  blocker () : done (false) {}

  void
  notify ()
  {
    std::unique_lock<std::mutex> lock (m);
    done = true;
    c.notify_all (); 
  }

  void
  wait ()
  {
    std::unique_lock<std::mutex> lock (m);
    while (!done)
      c.wait (lock);
  }

  bool done;
  std::mutex m;
  std::condition_variable c;
};
于 2012-12-08T15:31:03.900 回答