gpt4 book ai didi

c++ - std::thread 从函数开始而不等待线程完成

转载 作者:行者123 更新时间:2023-11-27 23:46:30 27 4
gpt4 key购买 nike

<分区>

如果我评论 t.join()

,我会很困惑地看到这个小程序中止
void my_thread()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "thread completed\n";
}

void main()
{
std::cout << "starting thread...\n";
std::thread t(my_thread);

t.join(); //<=== my program aborts when I comment this line

std::cout << "press a key to quit..." << std::endl;
std::getchar();
}

我想写一个不等待线程完成的函数。

我应该如何修复这个工作示例?

#include <iostream>
#include <thread>
#include <chrono>

void my_thread()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "thread completed\n";
}

void send_message()
{
std::cout << "starting thread...\n";

std::thread t(my_thread);

t.join(); //<=== the function aborts when I comment this line
}

void main()
{
send_message();
std::cout << "press a key to quit..." << std::endl;
std::getchar();
}

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