C++使用类成员函数作为线程启动函数

C++使用类成员函数作为线程启动函数

1、使用非静态成员函数作为线程启动函数

示例:

#include<thread>
#include<iostream>
#include "Server.h"
#include<Windows.h>
#include<chrono>
using namespace std;
Server::Server()
	:loghelper(logfilename),stop(false)
{
	this->loghelper.consoleout = true;
}
Server::~Server()
{

}
///使用类自身的函数作为线程函数
void Server::Run()
{
	thread t(&Server::loop, this);
	t.detach();
}
///线程函数
void Server::loop()
{
	while (!this->stop)
	{
		tm tm = LogHelper::gettm();
		if (tm.tm_sec == 0)
		{
			string content = LogHelper::gettime();
			this->mylist.push_back(content);
			this->loghelper.LogDebug(content);
			Sleep(1000);
		}
		Sleep(100);
	}
}

或者这样子:

int main()
{
	std::cout << "主程序开始" << endl;
	Server server;
	//server.Run();
	thread th(&Server::loop, &server); //使用类成员函数,并传入类指针
    th.join();
	getchar();
}

2、使用静态成员函数作为线程启动函数

int main()
{
	std::cout << "主程序开始" << endl;
	Server server;
	//server.Run();
	//thread th(&Server::loop, &server);
	//th.join();
	thread th2(&Server::test, "test");//使用静态成员函数作为线程启动函数,“test"是传的参数
	th2.join();
	getchar();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章