gpt4 book ai didi

C++线程执行完后还是 `joinable()`?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:17:45 24 4
gpt4 key购买 nike

我有以下功能:

void threadProc(){
for (int i = 0; i < 5; ++i) {
std::cout << "\n thread #" << std::this_thread::get_id() << " says hi";
}
std::cout << "\n Finished executing thread #" << std::this_thread::get_id();
}

我正在按以下方式使用它:

int main(){
try {
std::thread t1(threadProc);
t1.join();

std::thread t2(threadProc);
HANDLE handle = t2.native_handle();
WaitForSingleObject(handle, INFINITE);
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
std::cout << "\n thread t2 is joinable: " << std::boolalpha << t2.joinable() << "\n\n";
}
catch (std::exception& ex){
std::cout << "\n\n " << ex.what() << "\n\n";
}
return 0;
}

这是输出:

thread #21300 says hi

thread #21300 says hi

thread #21300 says hi

thread #21300 says hi

thread #21300 says hi

Finished executing thread #21300

thread #2136 says hi

thread #2136 says hi

thread #2136 says hi

thread #2136 says hi

thread #2136 says hi

Finished executing thread #2136

thread t2 is joinable: true

然后当 try block 超出范围时它会崩溃,因为在 t2 上调用了 abort()

我的问题是,为什么 t2 仍然是 joinable(),即使它的 threadProc 已经结束?为什么没有处理完?

此外,我正在使用 WaitForSingleObject 来确保我一直等到 t2 完成处理。我还添加了 5 秒的等待时间,以确保它需要时间来完成处理。然而,还有一些事情没有完成。

我知道我可以使用 t2.join()t2.detach() 但为什么我必须这样做? t2 已经完成处理(我认为)。


编辑:我尝试了以下代码:

int main() {
try {
std::thread t1([]() {std::cout << "\n\n Hi from thread #" << std::this_thread::get_id(); });
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
catch (std::exception& ex) {
std::cout << "\n\n " << ex.what() << "\n\n";
}
return 0;
}

而且线程仍然是可连接的。我查找了 joinable 引用,他们说:

A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.

所以这不再与 WaitForSingleObject 相关。问题是为什么一个线程在执行完后仍然被认为是joinable()

我看过这个question这让我更加困惑,因为它指出当线程完成执行时它不是 joinable() 甚至在调用 join()detach().

最佳答案

The question is why a thread is still considered joinable() after it finished execution?

因为您可能想编写加入()它的代码。如果 t.joinable() 在终止时自动变为 false,那么将没有安全的方法来调用 t.join()。你可以这样写:

if (t.joinable()) {
t.join();
}

但是如果线程在 t.joinable() 返回 true 之后终止,但在调用者能够完成 t.join() 调用。

让线程在实际被 join()ed 之前保持可连接状态是描述起来更简单的行为,并且更容易编写正确使用它的代码。

关于C++线程执行完后还是 `joinable()`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42692538/

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