使用boost条件变量

viv*_*vek 0 c++ boost

我正在尝试使用代码来测试同步化的boost条件变量,这段代码会同步.但它只显示4个值这里有什么问题?,我怎么能解决它?

在Windows 7上使用vs 2012

提前致谢.

#include <iostream>
#include <queue>

#include "boost\thread.hpp"
#include "boost\timer.hpp"

using namespace std;

int counter;

boost::mutex m;
boost::condition_variable CworkDone;
bool workdone = true;

bool procOn = true;

void display()
{
while (procOn == true)
{
    boost::mutex::scoped_lock lock(m);      

    if (workdone)
    {
        cout<<counter<<endl;
        CworkDone.notify_one();
        workdone = false;
    }   
    else 
    {
        CworkDone.wait(lock);
    }
}

}

void increment()
{
for(int i = 0 ; i <10 ; ++i)
{

    boost::mutex::scoped_lock lock(m);

    if (!workdone)
    {
        boost::this_thread::sleep(boost::posix_time::millisec(500));
        ++counter;
        workdone = true;
        CworkDone.notify_one();
    }
    else
    {
        CworkDone.wait(lock);
    }
}
procOn = false;
}

   int main()
{
boost::thread dispthread(display);
boost::thread incthread(increment);
dispthread.join();
incthread.join();

}
Run Code Online (Sandbox Code Playgroud)

Nim*_*Nim 6

问题是类生产者/消费者问题.你现在的代码并没有多大意义 - 你不能使用单个条件变量来等待双方,(记住你在相同的情况下调用notify然后等待 - 在相同的条件下.)所以任何事情都可能发生.

您需要重构代码以使用两个条件变量,一个用于生产者,一个用于消费者,例如:

编辑:更新了纯c ++ 11实现,这应该是正确的.

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>

using namespace std;

mutex mutex_;
condition_variable con_, prd_;
atomic_bool done_{false}, process_{false}; // possibly overkill, but hey-ho
int counter = 0; // protected resource

void consumer()
{
  for (;;)
  {
    unique_lock<mutex> lock(mutex_);       // acquire the mutex before waiting
    // this is the correct way to wait on the condition (as highlighted by @Dale)
    con_.wait(lock, []{ return process_.load() || done_.load(); });
    if (!done_.load())
    {
      cout << counter << endl;
      process_.store(false);               // we're done with this item
      lock.unlock();                       // release before notifying
      prd_.notify_one();
    }
    else
      break;                               // we're done completely
  }
}

void producer()
{
  unique_lock<mutex> lock(mutex_);
  for (int i = 0; i < 10; ++i)
  {
    this_thread::sleep_for(chrono::milliseconds(500));
    ++counter;
    process_.store(true);                 // indicate that there is data
    con_.notify_one();
    // wait for the consumer to complete
    prd_.wait(lock, []{ return !process_.load(); });
  }
  done_.store(true);                      // we're done
  lock.unlock();                          // release before notifying
  con_.notify_one();
}

int main(void)
{
  thread c(consumer);
  producer();
  c.join();
}
Run Code Online (Sandbox Code Playgroud)

所以现在发生的是,消费者等待它的条件(并且只有生产者会调用notify()它),并且生产者一旦产生了一些东西,就会调用这个通知来唤醒客户端.然后客户端将致电notify()唤醒生产者.

如上所述,上述更新方法不应受到虚假唤醒问题的影响.这消除了对a的需要timed_wait.