C++ Boost进程间互斥锁和条件变量
我正在看两个进程共享互斥锁和条件变量的Boost示例代码: 但我不明白这里的互斥条件变量设计是如何工作的 初始过程调用:C++ Boost进程间互斥锁和条件变量,c++,boost,mutex,boost-interprocess,C++,Boost,Mutex,Boost Interprocess,我正在看两个进程共享互斥锁和条件变量的Boost示例代码: 但我不明白这里的互斥条件变量设计是如何工作的 初始过程调用: for(int i = 0; i < NumMsg; ++i){ scoped_lock<interprocess_mutex> lock(data->mutex); // Take mutex if(data->message_in){ data->cond_full.wait(lock);
for(int i = 0; i < NumMsg; ++i){
scoped_lock<interprocess_mutex> lock(data->mutex); // Take mutex
if(data->message_in){
data->cond_full.wait(lock); // Wait
}
if(i == (NumMsg-1))
std::sprintf(data->items, "%s", "last message");
else
std::sprintf(data->items, "%s_%d", "my_trace", i);
//Notify to the other process that there is a message
data->cond_empty.notify_one(); // Notify
//Mark message buffer as full
data->message_in = true;
}
bool end_loop = false;
do{
scoped_lock<interprocess_mutex> lock(data->mutex); // Take mutex
if(!data->message_in){
data->cond_empty.wait(lock); // Wait
}
if(std::strcmp(data->items, "last message") == 0){
end_loop = true;
}
else{
//Print the message
std::cout << data->items << std::endl;
//Notify the other process that the buffer is empty
data->message_in = false;
data->cond_full.notify_one(); // Notify
}
}
while(!end_loop);
for(int i=0;i互斥锁);//获取互斥锁
如果(数据->消息中){
数据->状态已满。等待(锁定);//等待
}
如果(i==(numsg-1))
std::sprintf(数据->项目,“%s”,“最后一条消息”);
其他的
std::sprintf(数据->项,“%s\u%d”,“我的跟踪”,i);
//通知另一个进程有消息
data->cond_empty.notify_one();//notify
//将消息缓冲区标记为已满
数据->消息_in=true;
}
第二个过程调用:
for(int i = 0; i < NumMsg; ++i){
scoped_lock<interprocess_mutex> lock(data->mutex); // Take mutex
if(data->message_in){
data->cond_full.wait(lock); // Wait
}
if(i == (NumMsg-1))
std::sprintf(data->items, "%s", "last message");
else
std::sprintf(data->items, "%s_%d", "my_trace", i);
//Notify to the other process that there is a message
data->cond_empty.notify_one(); // Notify
//Mark message buffer as full
data->message_in = true;
}
bool end_loop = false;
do{
scoped_lock<interprocess_mutex> lock(data->mutex); // Take mutex
if(!data->message_in){
data->cond_empty.wait(lock); // Wait
}
if(std::strcmp(data->items, "last message") == 0){
end_loop = true;
}
else{
//Print the message
std::cout << data->items << std::endl;
//Notify the other process that the buffer is empty
data->message_in = false;
data->cond_full.notify_one(); // Notify
}
}
while(!end_loop);
bool end\u loop=false;
做{
作用域锁定锁(数据->互斥锁);//获取互斥锁
如果(!data->message_in){
data->cond_empty.wait(lock);//等待
}
如果(std::strcmp(数据->项目,“最后一条消息”)==0){
结束循环=真;
}
否则{
//打印消息
std::cout items message_in=false;
data->cond_full.notify_one();//notify
}
}
while(!end_loop);
要调用
wait()
或notify()
两个进程都必须持有共享互斥体,因此如果一个进程处于wait()
状态,另一个进程肯定无法调用notify()
?wait在等待时释放互斥体,因此另一个线程可以获取互斥体并执行通知。
另请参见上的说明