C++多线程-chap1多线程入门5
这里,只是记录自己的学习笔记。
顺便和大家分享多线程的基础知识。然后从入门到实战。有代码。
知识点来源:
https://edu.51cto.com/course/26869.html
用一个线程的基类,来实现线程封装
1 #include <thread> 2 #include <iostream> 3 #include <string> 4 5 //Linux -lpthread 6 7 using namespace std; 8 9 //用类来管理线程的参数生命周期 10 class MyThread { 11 public: 12 13 //入口线程函数 14 void Main() { 15 cout << "Mythread Main " << name << ":" << age << endl; 16 } 17 18 string name = ""; 19 int age = 100; 20 }; 21 22 23 24 //用一个线程的基类,来实现线程封装 25 class XThread { 26 public: 27 virtual void Start() { 28 is_exit_ = false; 29 //如果子类想传入不同的参数,可以重载Start方法 30 th_ = std::thread(&XThread::Main, this); 31 } 32 33 virtual void Stop() { 34 is_exit_ = true; 35 Wait(); 36 } 37 38 virtual void Wait() { 39 if (th_.joinable()) { 40 th_.join(); 41 } 42 } 43 44 bool is_exit() { return is_exit_; } 45 46 private: 47 virtual void Main() = 0; 48 std::thread th_; 49 bool is_exit_ = false; 50 }; 51 52 class TestXThread :public XThread { 53 public: 54 void Main() override { 55 cout << "testXThread Main begin..ID:"<<this_thread::get_id() << endl; 56 57 while (!is_exit()) { 58 59 this_thread::sleep_for(100ms); 60 cout << "." << flush; 61 } 62 cout <<endl<< "testXThread Main End..ID:" <<this_thread::get_id()<< endl; 63 } 64 65 string name; 66 }; 67 68 69 70 int main(int argc, char* argv[]) { 71 72 //// 通过传递对象的成员函数来启动线程 73 //MyThread myth; 74 //myth.name = "test name 001"; 75 //myth.age = 20; 76 ////参数1:成员函数的指针 77 ////参数2:当前对象的地址 78 //thread th(&MyThread::Main, &myth); 79 //th.join(); 80 81 82 83 //编写线程基类 84 TestXThread testth; 85 testth.name = "TestXThread name"; 86 //start是显示,各个继承的子类,可以根据自己需要(比如,想传入不同的参数)去重载Start方法。 87 testth.Start(); 88 89 this_thread::sleep_for(3s); 90 91 testth.Stop(); 92 93 testth.Wait(); 94 getchar(); 95 96 97 return 0; 98 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2019-11-21 sockaddr和sockaddr_in的区别
2019-11-21 CentOS 6.6 升级GCC G++ (当前最新版本为v6.1.0) (完整)
2019-11-21 telnet: Unable to connect to remote host: Connection refused
2019-11-21 telnet: Unable to connect to remote host: No route to host
2019-11-21 IP地址转换函数
2019-11-21 Linux 网络通信 API详解【转载】
2019-11-21 linux 文件详细信息