gpt4 book ai didi

c++ - c++11 中的多线程?

转载 作者:太空狗 更新时间:2023-10-29 19:58:29 24 4
gpt4 key购买 nike

<分区>

好的,我正在使用 Mac 在 C++11 中学习多线程。据我所知,所有线程都是同时执行的。我从 here 中找到了以下代码

// thread example
#include <iostream> // std::cout
#include <thread> // std::thread

void foo()
{
std::cout << "\nIn foo \n";
}

void bar(int x)
{
std::cout << "\nIn bar \n";
}

int main()
{
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar,0); // spawn new thread that calls bar(0)

std::cout << "main, foo and bar now execute concurrently...\n";

// synchronize threads:
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes

std::cout << "foo and bar completed.\n";

return 0;
}

每次运行代码时,我都会得到奇怪的结果,如下例

m

aIIinnn ,bf aofroo o

and bar now execute concurrently... foo and bar completed.

我错过了什么?

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