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