#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
std::mutex mutex;
std::condition_variable cond;
void in_msg()
{
while(true)
{
std::chrono::milliseconds second(1000);
std::this_thread::sleep_for(second);
std::unique_lock<std::mutex> unique(mutex);
cond.notify_one();
}
}
void out_msg()
{
while(true)
{
std::unique_lock<std::mutex> unique(mutex);
cond.wait(unique);
unique.unlock(); //可以提前解锁
std::cout << "out_msg" << std::endl;
}
}
int main()
{
std::thread inthread(&in_msg);
std::thread outthread(&out_msg);
inthread.join();
outthread.join();
return 0;
}
$ g++ msg_queue.cpp -std=c++11 -pthread
$ ./a.out
out_msg
out_msg