#include <thread>
#include <iostream>
#include <string>
//Linux -lpthread
using namespace std;
class MyThread
{
public:
    // 线程入口函数
    // 成员函数
    void Main()
    {
        cout << "MyThread Main " << name << ":" << age;
    }
    string name;
    int age = 100;
};

// 自定义的线程基类
class XThread
{
public:
    virtual void Start()
    {
        is_exit_ = false;
        th_ = std::thread(&XThread::Main, this);
    }
    virtual void Stop()
    {
        is_exit_ = true;
        Wait();
    }
    virtual void Wait()
    {
        // 检查线程是否可以被 join .
        // 如果线程函数已经开始执行,或者已经执行完毕但尚未被“join”,则该线程处于可被“join”状态.
        // 如果线程函数还未开始执行,或者已经执行完毕且已经被“join”,则该线程处于不可被“join”状态。
        if (th_.joinable())
            th_.join();
    }
    bool is_exit() { return is_exit_; }
private:
    virtual void Main() = 0;
    std::thread th_;
    bool is_exit_ = false;
};

// 测试类: 测试自定义的基类
class TestXThread :public XThread
{
public:
    void Main() override
    {
        cout << "TestXThread Main begin" << endl;
        while (!is_exit())
        {
            this_thread::sleep_for(100ms);
            cout << "." << flush;
        }
        cout << "TestXThread Main end" << endl;
    }
    string name;
};
int main(int argc, char* argv[])
{
    TestXThread testth;
    testth.name = "TestXThread name ";
    testth.Start();
    this_thread::sleep_for(3s);
    testth.Stop();

    testth.Wait();
    getchar();

    MyThread myth;
    myth.name = "Test name 001";
    myth.age = 20;
    // 成员函数作为线程入口
    thread th(&MyThread::Main, &myth);
    th.join();

    return 0;
}