当前位置: 首页 > news >正文

专门做定制的网站网站开发 瀑布结构

专门做定制的网站,网站开发 瀑布结构,已经有域名 怎么做网站,北京最大做网站的公司此前&#xff0c;我对detach的理解是&#xff0c;当主线程退出后&#xff0c;子线程能够继续存在。实际上&#xff0c;当主线程退出后&#xff0c;子线程也随之结束了。先看一个例子&#xff1a; #include <iostream> #include <thread> #include <unistd.h>…

    此前,我对detach的理解是,当主线程退出后,子线程能够继续存在。实际上,当主线程退出后,子线程也随之结束了。先看一个例子:

#include <iostream>
#include <thread>
#include <unistd.h>using namespace std;int main()
{std::thread my_thread([]{while(1) {this_thread::sleep_for(chrono::seconds(1));cout << "in thread" << endl;}});this_thread::sleep_for(chrono::seconds(2));my_thread.detach(); cout << "after detach" << endl; 
}

 运行结果为:

in thread
after detach

问题一:主进程结束之后,子线程会跟着结束吗?

 这是关于detach的定义:

https://legacy.cplusplus.com/reference/thread/thread/detach/

Detaches the thread represented by the object from the calling thread, allowing them to execute independently from each other.

既然都allowing them to execute independently from each other了,为什么主进程退出的时候,子线程也跟着走了?在linux系统中,当主进程结束的时候,子进程确实会跟着结束的。那么问题来了,main执行完之后,主进程就结束了吗?是的,的确如此,上面的例子已经说明了这个结论。那么,main是如何结束的?因为调用了return。可是,我在代码中没有没有调用return?因为编译器自动给加了一句return 0。真的吗?真的,请看下图:

 

能否让主进程退出之后,不把子进程给结束掉呢?请看下例:

int main()
{std::thread my_thread([]{while(1) {this_thread::sleep_for(chrono::seconds(1));cout << "in thread" << endl;}});this_thread::sleep_for(chrono::seconds(2));my_thread.detach(); cout << "after detach" << endl; pthread_exit(nullptr);
}

主进程退出后,子线程依然活蹦乱跳的。这一次,由于主进程通过pthread_exit猝然长逝,来不及挥一挥衣袖,也来不及带走一个线程。

问题二:

    detach之后,如果子线程退出了,会发生什么?

“Both threads continue without blocking nor synchronizing in any way. Note that when either one ends execution, its resources are released.”

如果子线程退出了,主进程也会随之而去。真的吗?请看下例:

int main()
{std::thread my_thread([]{cout << "thread bye" << endl;exit(0);});this_thread::sleep_for(chrono::seconds(2));my_thread.detach(); cout << "main bye" << endl; 
}

运行结果验证了上述结论。所以,一直以来,我对detach一直有误区。detach,主要的还是把主进程和子线程分离了,使二者能够独立的运行。但是,他们依然同生共死,不离不弃。

总结出以下结论:

1.主进程结束时(调用return/exit),子线程会随之结束。可以通过pread_exit退出进程而不杀掉其子线程。

2.用detach分离子线程和主进程,二者任意一个结束,整个进程(包括线程都会结束)。

3.在main函数中,如果不显示的调用return,编译器会自动给加一句return 0。

http://www.yayakq.cn/news/586481/

相关文章:

  • 太原微网站建设成品网站短视频源码搭建免费
  • 湘乡网站建设网络营销理论与实务
  • 怎么样提升网站权重公众号模板制作精美
  • 网站二次开发是什么wordpress速度好慢
  • 深圳办公室装修装修公司seo的关键词无需
  • 做传奇网站营销策划与运营方案
  • 计算机网站设计怎么做网站建设好了怎么做推广
  • 离婚协议书正规模板济宁seo优化
  • 菏泽网站制作免费推广自己的产品
  • app网站下载免费wordpress 会议
  • 网站二次开发多少钱沈阳新联会是什么组织做什么
  • 旧域名怎么做新网站微信网站html5
  • 茶叶网站策划网站如何解除绑定域名
  • 网站退出率是什么意思wordpress设为中文
  • 大连网站制作建设WordPress添加ftp
  • asp网站管理系统源码网站用户注册怎么建
  • 平顶山网站建设电话网站内容页相关性怎么做
  • 设计网站建设莱芜怎样建设美食网站
  • 网站建设合同约定三年后郑州防控升级
  • 北京网站建设 app小程序开发教程视频
  • 烟台网站建设联系企汇互联专业包装设计案例分析
  • 蕲春县住房和城乡建设局网站微信推广工具
  • 做海报免费素材网站有哪些创意网站建设话术
  • 河池网站建设公司如何使用mysql数据库做网站
  • 响应式网站定制开发事件营销ppt
  • 做网站页面的视频设计需要的软件
  • 许昌做网站公司哪家专业wordpress主题 使用教程
  • 网站开发与建设课程设计wordpress 局部刷新
  • 高端建站是什么什么类型网站
  • 上海 食品网站设计拍卖网站模板