增强型静音和条件变量

Boost Interprocess mutexes and condition variables

本文关键字:条件 变量 增强型      更新时间:2023-10-16

我正在查看此启动示例代码的两个过程,它们之间共享一个sutex和条件变量:

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

等待在等待时释放哑光,因此另一个线程可以获取sutex并执行通知。