简体   繁体   English

std :: mutex :: lock阻止CPU使用

[英]std::mutex::lock blocking CPU usage

I want to be able to freeze and unfreeze a thread at will. 我希望能够随意冻结和解冻线程。
My current solution is done through callbacks and busy waiting with sleep. 我当前的解决方案是通过回调和忙于睡眠的方式完成的。 This is obviously not an optimal solution. 这显然不是最佳解决方案。

I'm considering having the main thread lock a mutex, then have the slave thread run a function that locks and unlocks the same mutex. 我正在考虑让主线程锁定一个互斥锁,然后让从线程运行一个锁定和解锁相同互斥锁的函数。
My worry is the possible CPU usage if it's a true busy wait. 我担心的是,如果这是真正的繁忙等待,可能会占用CPU。
My question, as such, is: how does STL in C++11 specify "blocking", and if it is a busy wait, are there less CPU intensive solutions (eg pthreads)? 因此,我的问题是:C ++ 11中的STL如何指定“阻塞”?如果等待很忙,是否有较少的CPU密集型解决方案(例如pthread)?

Have a look at this answer: Multithreading, when to yield versus sleep . 看一下这个答案: 多线程,何时屈服与睡眠 Locking a mutex (in the manner you've described), is a reasonable solution to your problem. 锁定互斥锁(按照您描述的方式)是解决问题的合理方法。

Here's an MSDN article that's worth a read. 这是一篇MSDN文章 ,值得一读。 Quote: 引用:

Until threads that are suspended or blocked become ready to run, the scheduler does not allocate any processor time to them, regardless of their priority. 在挂起或阻塞的线程准备好运行之前,调度程序不会为它们分配任何处理器时间,无论它们的优先级如何。

If a thread isn't being scheduled it's not being run. 如果未计划线程,则不会运行该线程。

While mutexes can be used, it is not an optimal solution because mutexes should be used for resource protection (see also this q/a) . 尽管可以使用互斥锁,但这并不是最佳解决方案,因为应该将互斥锁用于资源保护(另请参见此q / a) Usually, std::condition_variable instances are what you should be looking for. 通常,您应该寻找std::condition_variable实例。 It works as follows: 其工作方式如下:

  1. Create an instance of std::condition_variable and distribute it to your controlling thread and your controlled thread 创建一个std::condition_variable实例并将其分发到您的控制线程和受控线程
  2. In the controlled thread, create a std::unique_lock . 在受控线程中,创建一个std::unique_lock Pass it to one of the condition variable's wait methods 将其传递给条件变量的wait方法之一
  3. In the controlling thread, invoke one of the notify methods on the condition variable. 在控制线程中,在条件变量上调用notify方法之一。

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM