#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <unistd.h>
using namespace std;
//std::mutex mtx;
std::recursive_mutex rmtx;
std::condition_variable_any cv;
string str;
void consume ()
{
while(1)
{
cout<<"consume\n";
lock_guard<recursive_mutex> lock(rmtx);
cout<<"waiting.....\n";
cv.wait(rmtx);
cout<<"get......\n";
cout<<str<<endl;
}
}
void run()
{
int i = 0;
while (1) {
{
cout<<++i<<endl;
lock_guard<recursive_mutex> lock(rmtx);
cout<<"has lock..\n";
cin>>str;
}
cv.notify_one();
usleep(1000);
}
}
int main ()
{
std::thread consumer_thread (consume);
std::thread t(run);
consumer_thread.join();
t.join();
return 0;
}
build:
g++ -std=c++11 cond.cpp -lpthread
注意:thread的实现依赖于pthread_create 不加pthread库,有的编译器会报错,有的不会(直接运行的时候就GG了)。