gpt4 book ai didi

c++ - boost::interprocess 互斥量和条件变量

转载 作者:行者123 更新时间:2023-11-30 03:24:03 26 4
gpt4 key购买 nike

我正在查看两个进程共享互斥锁和条件变量的 Boost 示例代码:

https://www.boost.org/doc/libs/1_57_0/doc/html/interprocess/synchronization_mechanisms.html

但我不明白这里的互斥条件变量设计是如何工作的。

初始流程调用:

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);

要调用 wait()notify() 任一进程都必须持有共享互斥锁,因此如果一个进程在 wait() 上另一个肯定不能调用notify()

最佳答案

wait 在等待时释放互斥锁,这样其他线程就可以获取互斥锁并执行通知。另见关于 https://www.boost.org/doc/libs/1_57_0/doc/html/interprocess/synchronization_mechanisms.html#interprocess.synchronization_mechanisms.conditions.conditions_whats_a_condition 的描述.

关于c++ - boost::interprocess 互斥量和条件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50026772/

26 4 0