不以物喜,不以己悲

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();
}
posted @   这种人  阅读(4827)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示