C++多线程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         th_ = std::thread(&XThread::Main, this);
30     }
31 
32     virtual void Stop() {
33         is_exit_ = true;
34         Wait();
35     }
36 
37     virtual void Wait() {
38         if (th_.joinable()) {
39             th_.join();
40         }
41     }
42 
43     bool is_exit() { return is_exit_; }
44 
45 private:
46     virtual void Main() = 0;
47     std::thread th_;
48     bool is_exit_ = false;
49 };
50 
51 class TestXThread :public XThread {
52 public:
53     void Main() override {
54         cout << "testXThread Main begin..ID:"<<this_thread::get_id() << endl;
55 
56         while (!is_exit()) {
57 
58             this_thread::sleep_for(100ms);
59             cout << "." << flush;
60         }
61         cout <<endl<< "testXThread Main End..ID:" <<this_thread::get_id()<< endl;
62     }
63 
64     string name;
65 };
66 
67 
68 
69 int main(int argc, char* argv[]) {
70 
71     //// 通过传递对象的成员函数来启动线程
72     //MyThread myth;
73     //myth.name = "test name 001";
74     //myth.age = 20;
75     ////参数1:成员函数的指针
76     ////参数2:当前对象的地址
77     //thread th(&MyThread::Main, &myth);
78     //th.join();
79 
80 
81 
82     //编写线程基类
83     TestXThread testth;
84     testth.name = "TestXThread name";
85     testth.Start();
86 
87     this_thread::sleep_for(3s);
88 
89     testth.Stop();
90 
91     testth.Wait();
92     getchar();
93 
94 
95     return 0;
96 }

 

上一篇:python-面向对象(一)


下一篇:java中的关联