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();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM