【发布时间】:2018-08-09 19:16:24
【问题描述】:
我正在尝试了解多线程的工作原理。
我有这个代码:
#include <iostream>
#include <thread>
#include <chrono>
void function1() {
std::cout << "Hi I'm the function 1" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Hi I'm the function 1 after sleeping" << std::endl;
}
void function2() {
std::cout << "Hi I'm the function 2" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "Hi I'm the function 2 after sleeping" << std::endl;
}
int main()
{
while(true) {
std::thread t1(function1);
std::thread t2(function2);
t1.join();
t2.join();
}
system("pause");
return 0;
}
问题是当我运行它时,它会停止等待std::this_thread::sleep_for(std::chrono::seconds(5));,并且不会在下一个循环中显示来自std::thread t1(function1); 的下一个Hi I'm the function 1,直到睡眠线程结束。
1) 你知道为什么吗?
2) 我希望 main 继续循环,不要等到 t2 完成(function2 中的 sleep_for() 设置为 5 秒)
【问题讨论】:
-
“你知道为什么吗?”因为您对其进行了编程以做到这一点。您启动两个线程,然后等到 both 完成。然后重新开始。如果您希望一个连续循环并且不等待另一个,则需要对 that 进行编程。
-
我怀疑你真的打算在你的线程内部有循环,但是如果你没有告诉我们,你很难知道你想做什么。
-
是的,我想休眠线程,在其他程序中我想使用它,例如在游戏中,我需要在每次按键之间设置延迟,但同时我需要知道是否键被按下 GetAsyncKeyState()。
标签: c++ multithreading performance sleep thread-sleep