I have a data structure :
struct {
mutex m;
condition_variable cv_p2c;
queue<int> qi;
bool finished;
} sdf_inst;
and I have a producer that generate 100 integer and insert them into queue qi after getting lock.
void producer () {
for(int i = 0 ; i < 100 ; i++ ) {
{
unique_lock<mutex> ulck(sdf_inst.m);//LOCK
sdf_inst.qi.push(i);
cout<<"adding "<<i<<endl<<flush;
}
sdf_inst.cv_p2c.notify_one();
}
unique_lock<mutex> ulck(sdf_inst.m);//LOCK
sdf_inst.finished=true;
sdf_inst.cv_p2c.notify_one();
}
After all datas have been inserted, it will acquire the lock and set the finished flag, and exit.
And I have another consumer :
void consumer () {
while(true) {
unique_lock<mutex> ulck(sdf_inst.m);//LOCK
sdf_inst.cv_p2c.wait(ulck,[]{return sdf_inst.qi.empty()==false || sdf_inst.finished==true ; });
print_all();
if(sdf_inst.finished=true) return;
}
}
It just acquire lock, and wait for notify from producer, and print all the data currently in the queue qi with the print_all function below:
void print_all () {
while(sdf_inst.qi.empty()==false) {
int i = sdf_inst.qi.front();
sdf_inst.qi.pop();
cout<<"shared_i "<< i <<endl<<flush;
}
return;
}
I think it should print all the 100 data, but sometimes it print only part of them.
I have studied the code carefully and find no error in synchronization, so may the lost data caused by the queue leakage?
Aucun commentaire:
Enregistrer un commentaire