请说明条件变量在c ++线程中的用法,以及为什么我们需要与此一起使用`unique_lock`和`mutex`

Nilesh

我指的是这段特定的代码:

该代码基本上具有三个线程1.与服务器进行一些握手2.从XML文件加载数据。3.对从XML加载的数据进行处理。我们可以看到任务1不依赖于任何其他任务,但是任务3依赖于任务2。因此,这意味着任务1和任务2可以由不同的线程并行运行以提高应用程序的性能。因此,应用程序被构建为多线程的。

#include <iostream>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>
using namespace std::placeholders;

class Application
{
  std::mutex m_mutex;
  std::condition_variable m_condVar;
  bool m_bDataLoaded;
public:
  Application()
  {
    m_bDataLoaded = false;
  }
  void loadData()
  {
   // Make This Thread sleep for 1 Second
   std::this_thread::sleep_for(std::chrono::milliseconds(1000));
   std::cout<<"Loading Data from XML"<<std::endl;
   // Lock The Data structure
   std::lock_guard<std::mutex> guard(m_mutex);
   // Set the flag to true, means data is loaded
   m_bDataLoaded = true;
   // Notify the condition variable
   m_condVar.notify_one();
  }
  bool isDataLoaded()
  {
    return m_bDataLoaded;
  }
  void mainTask()
  {
    std::cout<<"Do Some Handshaking"<<std::endl;
    // Acquire the lock
    std::unique_lock<std::mutex> mlock(m_mutex);
    // Start waiting for the Condition Variable to get signaled
    // Wait() will internally release the lock and make the thread to block
    // As soon as condition variable get signaled, resume the thread and
    // again acquire the lock. Then check if condition is met or not
    // If condition is met then continue else again go in wait.
    m_condVar.wait(mlock, std::bind(&Application::isDataLoaded, this));
    std::cout<<"Do Processing On loaded Data"<<std::endl;
  }
};
int main()
{
   Application app;
   std::thread thread_1(&Application::mainTask, &app);
   std::thread thread_2(&Application::loadData, &app);
   thread_2.join();
   thread_1.join();
   return 0;
}

此代码来自http://thispointer.com/c11-multithreading-part-7-condition-variables-explained/

谢谢

汉弗莱·温尼巴哥

条件变量允许原子释放一个持有的互斥体并使线程进入睡眠状态。然后,在收到信号后,以原子方式重新获取互斥锁并唤醒。例如,您在生产者/消费者问题中遇到了这种情况。死锁,如果你去睡觉,同时持有互斥,但如果你释放它睡觉前(由缺少信号唤醒),你也可以死锁。

在没有示例的情况下,不能用几个段落来解释它,并且使用条件变量存在一些众所周知的陷阱和警告。查阅Andrew D. Birrell撰写的“线程编程简介”。

无论使用哪种语言,条件变量始终使用互斥量。调用wait时必须保留互斥量。从等待返回后,您应始终验证所需条件是否仍然为真。这就是为什么您总是看到条件等待包裹在while循环中的原因。C ++ 11还为您提供谓词重载,这是while循环的语法糖。

互斥锁保护共享状态。该状况使您可以阻塞直到发信号为止。

unique_lock是用于锁定和解锁给定互斥锁的RAII(资源获取是初始化)包装。从概念上讲,它与lockC#中语句相同通过将互斥锁的获取和释放绑定到unique_lock实例的生存期,可以简化异常处理condition_variable除了这是一种好的做法,我不知道是否有迫使您使用它的原因unique_lock之间的唯一区别lock_guardunique_lock可以解锁...这就是为什么必须使用它而不是lock_guardwith的原因condition_variable

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档