zoukankan      html  css  js  c++  java
  • 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();
    }
    
  • 相关阅读:
    开源情报 Advise
    介绍几本搜索引擎的基础书
    Internet上的图像检索技术
    交易系统 转 武胜
    MySql数据库导出csv 武胜
    C# Process.Start()方法详解 武胜
    转 嵌入处部程序 武胜
    网际风通视接口 武胜
    C# Process运行cmd命令的异步回显 武胜
    RBreaker 武胜
  • 原文地址:https://www.cnblogs.com/zzr-stdio/p/14323825.html
Copyright © 2011-2022 走看看