condition_variable, wait, notify_one
#include <iostream>
#include <thread>
#include <vector>
#include <string>
#include <queue>
#include <mutex>
using namespace std;
class A {
public :
void inMsg ( ) {
for ( int i = 0 ; i < 10000 ; i++ ) {
cout << "插入一个元素:" << i << endl;
std:: unique_lock< mutex> myguard ( myMutex) ;
myQueue. push ( i) ;
my_cond. notify_one ( ) ;
}
}
void outMsg ( ) {
int command;
while ( 1 ) {
std:: unique_lock< std:: mutex> myguard ( myMutex) ;
my_cond. wait ( myguard, [ this ] {
if ( ! this - > myQueue. empty ( ) )
return true ;
return false ;
} ) ;
command = myQueue. front ( ) ;
myQueue. pop ( ) ;
cout << "取出一个元素:" << command << endl;
myguard. unlock ( ) ;
}
}
private :
queue< int > myQueue;
mutex myMutex;
std:: condition_variable my_cond;
} ;
int main ( ) {
A myobj;
thread outObj ( & A:: outMsg, & myobj) ;
thread inObj ( & A:: inMsg, & myobj) ;
outObj. join ( ) ;
inObj. join ( ) ;
cout << "hello,world!" << endl;
return 0 ;
}
notify_all
notify_one只通知一个线程,假如有2个out线程,1个in线程,那么in线程里的notify_one会随机唤醒其中一个out线程
#include <iostream>
#include <thread>
#include <vector>
#include <string>
#include <queue>
#include <mutex>
using namespace std;
class A {
public :
void inMsg ( ) {
for ( int i = 0 ; i < 10000 ; i++ ) {
cout << "插入一个元素:" << i << endl;
std:: unique_lock< mutex> myguard ( myMutex) ;
myQueue. push ( i) ;
my_cond. notify_one ( ) ;
}
}
void outMsg ( ) {
int command;
while ( 1 ) {
std:: unique_lock< std:: mutex> myguard ( myMutex) ;
my_cond. wait ( myguard, [ this ] {
if ( ! this - > myQueue. empty ( ) )
return true ;
return false ;
} ) ;
command = myQueue. front ( ) ;
myQueue. pop ( ) ;
cout << "取出一个元素:" << command << "thread id = " << std:: this_thread:: get_id ( ) << endl;
myguard. unlock ( ) ;
}
}
private :
queue< int > myQueue;
mutex myMutex;
std:: condition_variable my_cond;
} ;
int main ( ) {
A myobj;
thread outObj ( & A:: outMsg, & myobj) ;
thread outObj2 ( & A:: outMsg, & myobj) ;
thread inObj ( & A:: inMsg, & myobj) ;
outObj. join ( ) ;
outObj2. join ( ) ;
inObj. join ( ) ;
cout << "hello,world!" << endl;
return 0 ;
}
notify_all会唤醒所有out线程,但是因为只有一个线程能拿到锁,所以输出差不多。只不过这次有一个线程是被唤醒着等待(休眠)