邱邱玩编程 2022-03-19 10:01 采纳率: 100%
浏览 41
已结题

C++ thread 在堆内申请创建线程对象,线程会直接运行而不需要join、detach,这是为什么?

C++ thread 在堆内申请创建线程对象,线程会直接运行而不需要join、detach,这是为什么?
请看相关源码:
#include <iostream>
#include <thread>
#include <functional>
using namespace std;

void test()
{
  cout << "线程已启动" << endl;
  int i = 90;
  while(--i > 0)
  {
    cout << i << endl;
  }
  cout << "线程结束" << endl;
}

int main()
{
  thread *t1 = new thread(test);
  int i = 900000;
  while(--i > 0) ;

  return 0;
}
运行结果:

img

另以下方式也是直接运行,同样让人不解:

  thread th_;
  th_ = thread(test);
  int i = 900000;
  while(--i > 0) ;
我不明白这里为什么可以直接运行,希望在此请教大家
  • 写回答

2条回答 默认 最新

  • 真相重于对错 2022-03-19 12:38
    关注

    本来就是如此啊
    join只是阻塞当前线程,直到线程结束

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月27日
  • 已采纳回答 3月19日
  • 修改了问题 3月19日
  • 修改了问题 3月19日
  • 展开全部