gpt4 book ai didi

c++ - 为什么线程在这段代码中似乎不是并行运行的?

转载 作者:行者123 更新时间:2023-11-30 02:47:10 28 4
gpt4 key购买 nike

这是我第一次使用线程,如果这是一个不好的问题,我很抱歉。输出不应该由“随机化”电源和 foos 组成吗?我得到的似乎是一列 foos 和一列 mains。

#include <iostream>
#include <thread>

void foo() {

for (int i = 0; i < 20; ++i) {
std::cout << "foo" << std::endl;
}
}


int main(int argc, char** argv) {

std::thread first(foo);
for (int i = 0; i < 20; ++i) {
std::cout << "main" << std::endl;
}
first.join();
return 0;
}

最佳答案

有一个开始踩踏的头顶。所以在这个简单的例子中,输出是完全不可预测的。两个 for 循环都运行非常短,因此如果线程启动仅晚一毫秒,两个代码段将按顺序执行而不是并行执行。但是如果操作系统首先调度线程,则“foo”序列会显示在“main”序列之前。

在线程和主函数中插入一些sleep调用,看看它们是否真的并行运行。

#include <iostream>
#include <thread>
#include <unistd.h>

void foo() {

for (int i = 0; i < 20; ++i) {
std::cout << "foo" << std::endl;
sleep(1);
}
}


int main(int argc, char** argv) {

std::thread first(foo);
for (int i = 0; i < 20; ++i) {
std::cout << "main" << std::endl;
sleep(1);
}
first.join();
return 0;
}

使用线程不会自动强制代码段的并行执行,因为如果你在您的系统中只有一个 CPU,执行在所有进程和线程之间切换,并且代码段从不并行运行。

关于 threads here 有一篇很好的维基百科文章.尤其要阅读有关“多线程”的部分。

关于c++ - 为什么线程在这段代码中似乎不是并行运行的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22906206/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com