今天我们来扩展c++多线程学习中的关于线程入口并封装线程基类接口的内容,这部分内容也是相对来说比较重要的,涉及到类与成员函数,还有几个比较常见又陌生的概念。下面让我们一起来看看吧。
首先下面是基本接口的调用:

下面是样例代码:
#include<iostream>
#include<thread>
#include<string>
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()
{
if (th_.joinable())
{
th_.join();
}
}
bool is_exit()
{
return is_exit_;
}
private:
virtual void Main() = 0;//纯虚函数,不用实现
std::thread th_;//维护th_的对象
bool is_exit_ = false;
};
class TestXthread:public Xthread
{
public:
void Main()override//确保不会写错,不要等到编译才报错
{
cout << "begin" << endl;
cout << "TestXTHREAD Main" << endl;
while (!is_exit())
{
this_thread::sleep_for(100ms);
cout << "." << flush;//加个flush来刷新,确保点会显示
}
cout << "end" << endl;
}
string name;
};
//主线程入口
int main(int argc,char* argv[])
{
TestXthread testth;//启动基类线程
testth.name = "TestXThread name";
testth.Start();
this_thread::sleep_for(3s);//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;
}
程序执行图:...执行了3s后停下来。

好啦,关于c++多线程的线程入口并封装线程基类接口这部分内容就到这啦,由于博主现在也正在学习这部分内容,若有错误和建议,请评论区指出哦。
本贴为博主亲手整理。如有错误,请评论区指出,一起进步。谢谢大家的浏览.
本文介绍了C++中多线程的线程入口和基类封装,通过示例代码展示了如何创建线程基类、启动与停止线程以及线程的等待操作。同时,讲解了如何使用成员函数作为线程入口,并通过TestXthread类实现了具体的线程功能。在主函数中,演示了如何启动和停止线程。
887

被折叠的 条评论
为什么被折叠?



