我正在尝试了解多线程的工作原理。
我有这个代码:
#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));
并且不显示下一个你好,我是来自
在下一个循环中,直到 sleep 线程结束。std::thread t1(function1);
的函数 1
1)你知道为什么吗?
2) 我希望 main 继续循环并且不要等待 t2 完成(function2 中的 sleep_for() 设置为 5 秒)
最佳答案
这就是您的代码所做的:
- 启动线程 1
- 输出一条消息
- 等待 1 秒
- 输出另一条消息
- 启动线程 2
- 输出一条消息
- 等待 5 秒
- 输出另一条消息
- 等待两个线程完成
- (这大约需要 5 秒)
- 无限期地重复
您已声明这不是您的本意。
我认为,相反,您打算让每个线程的“重复”内部,以便它们继续独立且无限期地滴答作响,如下所示:
#include <iostream>
#include <thread>
#include <chrono>
void function1() {
while (true) {
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() {
while (true) {
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()
{
std::thread t1(function1);
std::thread t2(function2);
t1.join();
t2.join();
}
现在您的代码执行此操作:
- 启动线程 1
- 输出一条消息
- 等待 1 秒
- 输出另一条消息
- 无限期地重复
- 启动线程 2
- 输出一条消息
- 等待 5 秒
- 输出另一条消息
- 无限期地重复
- 等待两个线程完成
- (尽管永远不会!)
现在每个线程都独立旋转,任何一个都不会“阻塞”另一个。
关于c++ - 线程和 sleep ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49054466/