MFC线程函数中访问成员变量的方法

用AfxBeginThread启动线程,线程的执行函数有两种定义的方法:

全局函数:UINT threadMessageBoxAdapter( LPVOID lParam );

静态成员函数:static UINT threadMessageBoxAdapter( LPVOID lParam );


若线程函数式全局函数,在线程中使用变量都必须是全局变量,不能使用对话框类成员变量,成员变量定义成static,才能在线程函数中访问成员变量。

若线程函数是静态成员函数,则也只能使用类静态成员变量。

这里说明一种在线程函数中访问成员变量的方法:

这里定义Thread类:

class Thread

{

public:

              static UINT threadMessageBoxAdapter( LPVOID lParam );//线程函数,静态成员函数

              UINT threadMessageBoxProc( );//类成员函数

private:

              CString strThreadText;

};

线程函数的实现:

UINT Thread::threadMessageBoxAdapter( LPVOID lParam )

{

              CTestVectorDlg* obj = ( CTestVectorDlg* )lParam;

              return obj->threadMessageBoxProc();

}

UINT Thread::threadMessageBoxProc()

{

              CString strThreadText;

              strThreadText.Format( _T( "%s" ), _T( "Thread adapter" ) );

              AfxMessageBox( strThreadText );

              return 0;

}

使用AfxBeginThread启动线程:

              CWinThread* thread;

              thread = AfxBeginThread( threadMessageBoxAdapter, this );

这样,当线程启动后,弹出”Thread Adapter”的信息,说明成功访问成员变量。

你可能感兴趣的:(MFC线程函数中访问成员变量的方法)