多线程创建(2)
成员函数作为线程入口并封装线程基类接口
- 使用前面的[多线程创建(1)](https://blog.csdn.net/Soledad1206/article/details/126512175)中的方法创建子线程,可以支持全局函数或者静态成员函数作为线程的入口函数
- 使用全局函数座位线程入口会存在变量的生命周期问题,即主函数中变量的内存已经被释放,但是线程还没有结束,会造成程序异常。
- 使用对象创建线程,可以使用成员变量减少冗余的变量,直接将对象本身作为线程参数传入。
#include<iostream>
#include<string>
#include<thread>
using namespace std;
class myThread
{
public:
void Main()
{
cout << "myThread Main" << name << endl;
}
string name;
};
int main(int argc, char** argv)
{
myThread th;
th.name = "Test myThread name 001";
thread th(&myThread::main, &th);
th.join();
return 0;
}
线程基类的封装
- 设计线程基类可以实现对于线程的封装,如果需要新建新的线程,直接从线程基类去继承就可以
- 使用线程基类,可以将线程生命周期的管理,线程的退出管理等放到线程基类中去做
#include<iostream>
#include<string>
#include<thread>
using namespace std;
class BaseThread
{
public:
virtual void Start();
virtual void Wait();
virtual void Stop();
bool is_exit();
private:
virtual void Main() = 0;
std::thread th_;
bool is_exit_ = false;
};
void BaseThread::Start()
{
is_exit_ = false;
th_ = std::thread(&BaseThread::Main, this);
}
void BaseThread::Wait()
{
if (th_.joinable())
th_.join();
}
void BaseThread::Stop()
{
is_exit_ = true;
}
bool BaseThread::is_exit()
{
return is_exit_;
}
class derivedThread : public BaseThread
{
public:
void Main() override;
string name;
};
void derivedThread::Main()
{
cout << "Test derivedThread Main begin!" << endl;
while (!is_exit())
{
std::this_thread::sleep_for(100ms);
cout << "." << flush;
}
cout << endl << "Test derivedThread Main end!" << endl;
}
int main(int argc, char** argv)
{
derivedThread testth;
testth.name = "derivedThread test name 002";
testth.Start();
this_thread::sleep_for(3s);
testth.Stop();
testth.Wait();
return 0;
}