zoukankan      html  css  js  c++  java
  • C++类中创建线程

    ​ 经常会遇到需要在类中创建线程,可以使用静态成员函数,并且将类实例的指针传入线程函数的方式来实现。

    实现代码代码如下:

    /* 类头文件 CTestThread.h */
    #include<iostream>
    #include<process.h>
    #include<Windows.h>
    
    class TestThread
    {
    public:
    	TestThread();
    	~TestThread();
    
    	 int StartThread();  // 开线程
    	 int SetStopFlag(bool flag); //停止线程
    
    private:
    	static unsigned int WINAPI ThreadFunc(LPVOID lpParam);  //线程函数
    
    private:
    	bool m_bStopFlag;
    };
    
    
    
    /* 类源文件 CTestThread.cpp */
    
    #include "CTestThread.h"
    
    TestThread::TestThread()
    {
    	m_bStopFlag = false;
    }
    
    TestThread::~TestThread()
    {
    	m_bStopFlag = true;
    
    }
    
    
    int TestThread::StartThread()
    {
    	HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ThreadFunc, (LPVOID)this, 0, NULL);
    
    	return 0;
    }
    
    int TestThread::SetStopFlag(bool flag)
    {
    	m_bStopFlag = flag;
    	return 0;
    }
    
    unsigned int WINAPI TestThread::ThreadFunc(LPVOID lpParam)
    {
    	TestThread* pthis = (TestThread*)lpParam;
    	while (!pthis->m_bStopFlag)
    	{
    		printf("ThreadFunc is running cassid is %d .
    ",pthis->m_classid);
    		Sleep(1000);
    	}
    	printf("ThreadFunc return.
    ");
    	return 0;
    }
    
    
    /* 测试代码 test.cpp */
    
    #include "CTestThread.h"
    
    int main()
    {
    	TestThread testThread(1);
    	testThread.StartThread();
    
    	char ch;
    	while (ch = getchar())
    	{
    		if (ch == 'q' || ch == 'Q')
    		{
    			testThread.SetStopFlag(true);
    			break;
    		}	
    		Sleep(1000);
    	}
    }
    
  • 相关阅读:
    Linux 查看CPU信息,机器型号,内存等信息
    TCPdump抓包命令详解
    nginx https 转发
    滚动效果
    phpexcel中文手册(转)
    Java数组操作十大方法 (转)
    ajax防止重复提交
    信用评分卡(A卡/B卡/C卡)的模型简介及开发流程|干货
    求方差分析与两样本T检验 区别
    互联网运营中的10大数据分析方法
  • 原文地址:https://www.cnblogs.com/ay-a/p/11409233.html
Copyright © 2011-2022 走看看