mfc 创建线程函数AfxBeginThread,线程中访问mfc控件

来源:互联网 发布:淘宝优惠微信群 编辑:程序博客网 时间:2024/06/08 14:36

转字http://blog.csdn.net/guomsh/article/details/10377993

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;
   }
0 0