c++ - 如何无阻塞加入到标准线程
问题描述
我想保持我的代码干净并做正确的事情,任何std::thread
我需要做的加入或分离,但我怎样才能(在主线程)等待另一个线程而不阻塞主线程的执行?
void do_computation()
{
// Calculate 1000 digits of Pi.
}
int main()
{
std::thread td1(&do_computation);
while (running)
{
// Check if thread td1 finish and if yes print a message
// Here are some stuff of the main to do...
// Print to UI, update timer etc..
}
// If the thread has not finished yet here, just kill it.
}
解决方案
答案是信号量。您可以使用二进制信号量来同步您的线程。
您可以使用 System V信号量或pthread互斥锁,但它们在某种程度上是 C++ 中的遗留物。不过,使用Tsuneo Yoshioka 的回答,我们可以实现 C++ 的信号量方式。
#include <mutex>
#include <condition_variable>
class Semaphore {
public:
Semaphore (int count_ = 0)
: count(count_) {}
inline void notify()
{
std::unique_lock<std::mutex> lock(mtx);
count++;
cv.notify_one();
}
inline void wait()
{
std::unique_lock<std::mutex> lock(mtx);
while(count == 0){
cv.wait(lock);
}
count--;
}
private:
std::mutex mtx;
std::condition_variable cv;
int count;
};
您的实现可能会使用Semaphore
该类,就像这样。
void do_computation()
{
//calculate 1000 digits of Pi.
semaphore.notify();
}
int main()
{
Semaphore semaphore(0);
std::thread td1(&do_computation);
semaphore.wait();
}
推荐阅读
- exchangewebservices - ExchangeWebService 预约响应选项
- python - 如何从另一个数据帧更新一个数据帧的特定列
- vb.net - 使用 CsvHelper 在现有 CSV 文件中添加新列
- git - 从 git 中删除未跟踪的文件
- c# - 从文本文件中读取行并自动分配变量
- python - 无法打开“util.pxd”:找不到文件(file:///c:/users/wojciech/desktop/python_labs/pandas/src/util.pxd)
- dialogflow-es - 如何在 Dialogflow 中构建 Intent
- c - calloc() 总共可以分配超过 SIZE_MAX 吗?
- raspberry-pi - 如何使用 OMNET++ 进行硬件循环实验
- html - 为什么我们不能在角度 6 中的相同输入标签中使用 [(ngModel)] 和值