肥宅自学平台_人人成为技术开发者

肥宅人只等待您,联系我们吧,曾经的巅峰是否能回来?我们正在用心服务!

C++ 多线程使用怎么使用多线程不卡

 更新时间:2023-09-27 07:58:59   作者:肥宅-季波   我要评论(0)  

         最近在做C++的开发,其中很多地方需要使用到多线程,故记录在此。

头文件:#include <thread>,命名空间:std

std::thread是C++11之后的标准线程库,使用起来很方便。

主要有以下几种使用方式:

新线程执行一个函数
  1. #include <iostream>
  2. #include <thread>
  3. using namespace std;
  4. void t1()
  5. {
  6.     for (int i = 0; i < 10; ++i)
  7.     {
  8.         cout << "thread-1\n";
  9.     }
  10. }
  11. void t2(int n)
  12. {
  13.     for (int i = 0; i < n; ++i)
  14.     {
  15.         cout << "thread-2\n";
  16.     }
  17. }
  18. int main()
  19. {
  20.     thread th1(t1);  //没有参数时
  21.     thread th2(t2,10); //有参数时
  22.     th1.join(); // 必须将线程join或者detach 等待子线程结束主进程才可以退出,detach是用来和线程对象分离的,这样线程会独立地执行
  23.     th2.join();
  24.     //or use detach
  25.     //th1.detach();
  26.     //th2.detach();
  27.     cout << "main thread\n";
  28.     return 0;
  29. }
类外新线程执行一个成员函数
  1. #include <iostream>
  2. #include <thread>
  3. using namespace std;
  4. class Client{
  5.     void recieve();
  6.     void recieve(int conn);
  7. }
  8. int main()
  9. {
  10.         Client *client=new Client();//此处必须使用指针
  11.     thread t1(&Client::recieve,client);//没有参数时
  12.     thread t2(&Client::recieve,client,1);//有参数时
  13.     t1.join();
  14.     t2.join();
  15.     return 0;
  16. }
类中新线程执行成员函数
  1. #include <iostream>
  2. #include <thread>
  3. using namespace std;
  4. class Client{
  5.     void recieve();
  6.     void recieve(int conn);
  7.    
  8.     Client(){
  9.         thread t1(&Client::recieve,this);//没有参数时
  10.             thread t2(&Client::recieve,this,1);//有参数时
  11.         t1.detach();
  12.         t2.detach();
  13.     }
  14. }
  15. int main()
  16. {
  17.     while(true){
  18.         
  19.     }
  20.     return 0;
  21. }
"小礼物走一走,来肥宅自学平台支持我"
评论区

评论

共条评论
  • 这篇文章还没有收到评论,赶紧来抢沙发吧~
客服中心在线客服
全心全意为平台用户服务
Copyright © 2017-2023 自学平台网站地图:去查看>
  • 肥宅人自己的自学平台
  • 人人都能成为平台讲师
  • 贡献你的力量壮大肥宅自学平台
  • 将自己的能力变现
  • 实现人生的第二职业
网址收藏平台安卓APP
微信公众号微信公众号

本站部分图片或者资源来自程序自动采集或卖家(商家)发布,如果侵犯了您的权益请与我们联系,我们将在24小时内删除!谢谢!

肥宅自学教程网是一个主打IT视频教程、自媒体运行、摄影剪辑等内容的资源学习交流平台。