- 注册时间
 - 2021-4-16
 
- 最后登录
 - 2025-1-4
 
- 在线时间
 - 5 小时
 
 
 
 
 
编程入门 
  
	- 龙马币
 - 54 
 
 
 
 
 | 
 
 
1. C++ 中如何定义线程函数 
 
     有两种方法: 
        a. 定义线程函数为全局函数     
        b. 定义线程函数为类的静态成员函数 
 
2. C++中的线程函数如何访问类中的成员变量 
 
    针对线程函数为类的静态成员进行说明。如果是静态数据成员,当然可以直接访问,但是如果要访问非静态数据成员,直接访问是做不到的。如果要想在线程函数中访问和操作类的非静态成员变量,可以把线程函数作为一个适配器,在适配器中调用类的非静态成员函数。 
 
例如: 
- class CMyClass
 
 - {
 
 - public:
 
 -     void TestFunc();
 
 -     static int ThreadFunc(LPVOID pParam);// Adapter
 
 - protected:
 
 -     int ThreadFuncKernal();// Kernal
 
 - }
 
  
- void CMyClass::TestFunc()
 
 -    {
 
 -         AfxBeginThread(TreadFunc, this);
 
 -    }
 
  
-    // Thread function Adapter
 
 -    int CMyClass::ThreadFunc(LPVOID pParam) //这个是线程,声明时使用static关键字 ,不能访问控件
 
 -    {
 
 -        CMyClass *pObj = (CMyClass *)pParam;
 
 -        return pObj->ThreadFuncKernal();
 
 -    }
 
  
-    // Thread function kernal
 
 -    int CMyClass::ThreadFuncKernal() //在这里可以访问mfc的控件
 
 -    {
 
 -        while(1)
 
 -        {
 
 -            // my thread
 
 -            // to control class non-static member
 
 -        }
 
 -        return 0;
 
 -    }
 
  复制代码 |   
 
 
 
 |