• 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();
    }
    
  • 相关阅读:
    电梯调度之调研报告
    小作业之测试篇
    求固定数组的最大子数组
    四则运算之C++实现篇
    四则运算2之设计思路篇
    轻松记账工程冲刺第十天
    轻松记账工程冲刺第九天
    轻松记账工程冲刺第八天
    简评QQ拼音输入法
    轻松记账工程冲刺第七天
  • 原文地址:https://www.cnblogs.com/zzr-stdio/p/14323825.html
Copyright © 2020-2023  润新知