【问题标题】:C++11 creating new threads in a detached threadC++11 在分离线程中创建新线程
【发布时间】:2013-08-28 08:43:24
【问题描述】:

我正在考虑从主线程创建std::threaddetach() 的可能性,而分离线程创建线程并在运行下一个线程之前等待join()

但我不认为这是可能的,因为我总是在第一个线程之后但在下一个线程之前崩溃。

代码中的某处:

std::thread t1(&B::start, this); //Launch a thread
t1.detach();

B::start内:

std::thread t2(&C::start, this); //Launch a thread
t2.join();

std::thread t3(&D::start, this); //Launch a thread
t3.join();

std::thread t4(&D::start, this); //Launch a thread
t4.join();

C::start内:

std::cout << "Thread t2 is starting" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_until(start + std::chrono::seconds(60));
std::cout << "Thread t2 waited for 60 seconds" << std::endl;

D::start内:

std::cout << "Thread t3 is starting" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_until(start + std::chrono::seconds(60));
std::cout << "Thread t3 waited for 60 seconds" << std::endl;

E::start内:

std::cout << "Thread t4 is starting" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_until(start + std::chrono::seconds(60));
std::cout << "Thread t4 waited for 60 seconds" << std::endl;

所以这就是我所期望的:

将创建一个线程 t1 并将其与主线程分离,以便主应用程序继续运行

t1 中,t2 被创建并休眠 60 秒。

60 秒后,t3 被创建并休眠 60 秒。

60 秒后,t4 被创建并休眠 60 秒。

我的主线程一直在做它的事情。

更新:如何将这个std::thread t1(&amp;B::start, this); //Launch a thread 分解,以便我在标题中声明std::thread t1;,但在需要的地方执行(&amp;B::start, this);,然后在detach();

【问题讨论】:

  • 在你的主线程中 std::thread t1.detach(); 之后发生了什么?如果它所在的对象被销毁,那么所有其他对象都可能崩溃,因为它是所有对象中的同一个对象。
  • t1 是在对象的构造函数中创建的,该对象被填充到向量中以供将来操作。你能看到我的更新吗?
  • 什么采取行动?你把它拆了。
  • 我怀疑你的第四个线程创建中有错字。
  • @Jason:你能提供一个 sscce 吗?

标签: c++ multithreading c++11 stdthread


【解决方案1】:

你为什么要分离你的第一个线程?无论如何,它将与您的主线程分开运行!

【讨论】:

  • ...更准确地说:在std::thread t1(&amp;B::start, this); 之后,线程正在运行!如果你以后想join它,你不应该detachit。
猜你喜欢
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 2013-02-03
  • 2013-03-28
  • 1970-01-01
相关资源
最近更新 更多