最近想试一下std::thread 来替换pthread,发现网络上都是用全局的变量来开启线程。
但是我一般倾向于在封装好的类中,直接开启新线程,对外仅仅保留调用接口。
所以自己调试了一个模板,供大家参考!
#include <iostream>
#include <thread>
using namespace std;
class ThreadFunc
{
public:
void start()
{
mydo = true;
std::cout << "线程函数被启动" << std::endl;
mT = new thread(&ThreadFunc::doT,this,15);
}
void stop ()
{
std::cout << "线程函数被停止" << std::endl;
mydo = false;
mT->join();
}
void doT(int a)
{
while(mydo)
{
cout<<"a:"<<a--<<endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
cout<<"线程exit"<<endl;
}
private:
thread* mT;
bool mydo = true;
};
int main()
{
ThreadFunc m_ThreadFunc;
m_ThreadFunc.start();
std::this_thread::sleep_for(std::chrono::seconds(5));
m_ThreadFunc.stop();
cout<<"main exit"<<endl;
return 0;
}