条件变量notify_one notify_all

时间:2015-04-05 08:10:25

标签: c++ multithreading c++11 notify condition-variable

我正在尝试学习条件变量,并且我坚持以下示例。我认为notify_one消费者应该只解锁一个等待的消费者。但在重复启动之后,在我看来情况并非如此。我已将notify_one更改为notify_all,但未发现行为发生变化。在制作人对消费者调用notify_one之后,我可以看到Get…被一个以上的消费者写在屏幕上。

为什么会这样?

#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
#include <chrono>
std::mutex mtx;
std::condition_variable produce,consume;

int cargo = 0;     // shared value by producers and consumers

void consumer () {
  std::unique_lock<std::mutex> lck(mtx);
  while (cargo==0) consume.wait(lck);
  std::cout << "Get" << cargo << " "<< std::this_thread::get_id() << '\n';
  cargo--;
  produce.notify_one(); 
}

void producer (int id) {
  std::unique_lock<std::mutex> lck(mtx);
  while (cargo!=0) produce.wait(lck);
    std::cout << "Push" << id <<  " "<< std::this_thread::get_id() << '\n';
    cargo += id;
    consume.notify_one();
}

void c () {
    while(1) {
    consumer();
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}
void p(int n) {
    while(1) {
        producer(n);
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

int main ()
{
    std::thread consumers[5],producers[5];

    for (int i=0; i<5; ++i) {
       consumers[i] = std::thread(c);
       producers[i] = std::thread(p,i+1);
    }

    for (int i=0; i<5; ++i) {
       producers[i].join();
       consumers[i].join();
    }

    return 0;
  }

0 个答案:

没有答案