做一个二手网站怎么做网站服务器查询
news/
2025/9/24 5:08:05/
文章来源:
做一个二手网站怎么做,网站服务器查询,嘉兴手机网站建设,携程网站建设的意义std::jthread是C20新引入的线程类#xff0c;与 std::thread 类似#xff0c;或者说#xff0c;jthread是对thread进一步的封装#xff0c;功能更强大。
std::jthread的j实际上是joining的缩写#xff0c;众所周知#xff0c;std::thread在其生命周期结束…std::jthread是C20新引入的线程类与 std::thread 类似或者说jthread是对thread进一步的封装功能更强大。
std::jthread的j实际上是joining的缩写众所周知std::thread在其生命周期结束时调用join()(让主线程等待该子线程完成然后主线程再继续执行对于不会停止的线程不要使用join()防止阻塞其他线程)或调用detach()(调用detach()进行线程分离使其不影响其他线程运行比如一个线程中无限循环执行的场景下需要detach()。如果join()和detach()都没有被调用析构函数将立即导致程序异常终止。C20引入的std::jthread得以解决这个问题std::jthread对象被析构时会自动调用join()等待执行流结束。
此外std::jthread支持外部请求中止操作调用join()后可能需要等待很长时间甚至是永远等待。std::jthread除了提供std::stop_token能够主动取消或停止正在执行的线程还增加了std::stop_callback允许在停止线程操作时调用一组回调函数。
来看看cpprefercence关于std::jthread::~jthread的解释 std::jthread::~jthread Destroys the jthread object. If *this has an associated thread (joinable() true), calls request_stop() and then join(). Notes The request_stop() has no effect if the jthread was previously requested to stop. A jthread object does not have an associated thread after it was default-constructedit was moved fromjoin() has been calleddetach() has been calledIf join() throws an exception (e.g. because deadlock is detected), std::terminate() may be called.
关于std::jthread::join的作用阻塞当前线程直至 *this 所标识的线程结束其执行。
看例程
#include iostream
#include thread
#include chronovoid foo()
{// 模拟耗费大量资源的操作std::this_thread::sleep_for(std::chrono::seconds(1));
}void bar()
{// 模拟耗费大量资源的操作std::this_thread::sleep_for(std::chrono::seconds(1));
}int main()
{std::cout starting first helper...\n;std::jthread helper1(foo);std::cout starting second helper...\n;std::jthread helper2(bar);std::cout waiting for helpers to finish... std::endl;helper1.join();helper2.join();std::cout done!\n;
}
输出结果如下 starting first helper...
starting second helper...
waiting for helpers to finish...
done! std::jthread::joinable主要是用来检查 std::jthread 对象是否标识活跃的执行线程直接看cpprefercence相关例程
#include iostream
#include thread
#include chronovoid foo()
{std::this_thread::sleep_for(std::chrono::seconds(1));
}int main()
{std::jthread t;std::cout before starting, joinable: std::boolalpha t.joinable() \n;t std::thread(foo);std::cout after starting, joinable: t.joinable() \n;t.join();std::cout after joining, joinable: t.joinable() \n;
}
输出结果如下 before starting, joinable: false
after starting, joinable: true
after joining, joinable: false 可知如果 jthread 对象标识活跃的执行线程则为 true 否则为 false 。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/914918.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!