c++ - 在间隔内运行函数,同时运行主代码
问题描述
基本上我试图同时运行 2 段代码而不冻结彼此,其中之一需要一些延迟。因此,初始代码如下所示:
int main() {
cout << "Hello World!";
std::this_thread::sleep_for(std::chrono::milliseconds(166)); // this freezes the whole program for 166 ms
// do other things
}
我想出了一个线程的方法:
void ThreadFunction() {
cout << "Hello World!";
std::this_thread::sleep_for(std::chrono::milliseconds(166));
}
int main() {
std::thread t1(ThreadFunction);
t1.detach();
// do other things while also doing what the thread t1 does without waiting 166ms
}
这不完全是我的代码,但我正在尝试重新创建作为示例的代码。
线程工作正常,但我听到人们说thread.detach()
不好。
那么有哪些替代方案呢?
解决方案
你的第二个例子似乎是你想要的。如果您不想分离线程,请不要这样做。但是,您必须join
这样做,并且您只能join
在某个线程完成工作时才可以使用它。
对于这个简单的例子,我建议如下(否则你需要一个条件变量或类似的信号来指示它应该停止的线程):
void ThreadFunction() {
for (int i=0; i <100; ++i) {
cout << "Hello World!";
std::this_thread::sleep_for(std::chrono::milliseconds(166));
}
}
int main() {
std::thread t1(ThreadFunction);
// do other things while also doing what the thread t1 does without waiting 166ms
t1.join(); // blocks until ThreadFunction returns
}
推荐阅读
- java - 有什么理由我不应该使用 FileReader?
- javascript - 将对象值添加到数组的现有虚线键
- sql-server - T-SQL 中的日期和小时虚拟表
- javascript - 如何告诉 ESLint 在当前文件之前包含另一个文件?
- html - 如何从选择标签中设置选项内文本之间的间距
- sql-server - 删除记录时“子查询返回超过 1 个值”,而不是如果我更改获取的数字
- ember.js - 如何在 Ember-bootstrap Modal 上添加一个类?
- android - 在 Android Pie 中禁用 sqlite Write-Ahead 日志记录
- angular - 角度解析器不适用于 Ionic v4 选项卡模板
- java - 为什么将数组传递给方法时出现找不到符号