UINT ThreadProc(LPVOID pParam)中的参数在MFC中怎么用呀

ma100 2004-11-22 11:34:39
如题,另外,什么时候调用AfxEndThread呀,我又不知道什么时候他结束
...全文
638 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
双杯献酒 2004-11-23
  • 打赏
  • 举报
回复
如果传递给线程的pParam是CWnd*,
不可以在线程中调用和窗口显示有关的函数。
因为CWnd是线程相关的。
老夏Max 2004-11-23
  • 打赏
  • 举报
回复
UINT ThreadProc(LPVOID pParam)中的参数在MFC中怎么用呀
===========================
可以将创建线程的类的this指针传递进去,例如:
void CPage3::LoadThumbImages()
{
TerminateThread();
m_hThread = (HANDLE)_beginthreadex(NULL,0, LoadThumbNail,(LPVOID)this,0/* CREATE_SUSPENDED*/,&m_dwThreadID);
m_bRunning = TRUE;
}

unsigned __stdcall CPage3::LoadThumbNail(LPVOID lpParam)
{
CPage3* pThumbDlg = (CPage3*)lpParam;
//使用对话框类的变量或者函数
CListCtrl& ListCtrl = pThumbDlg->m_cThumbList;
CImageList* pImgList = &pThumbDlg->m_ImageListThumb;
}

什么时候调用AfxEndThread呀,我又不知道什么时候他结束
==========================
线程函数执行完了,线程就结束了!!

仿多线程的效果一般有2种办法:第一种是通过定时器;第二种是启动多线程,不同模式下启动函数不同,mfc与API与WIN32下面注意点也是有区别的! VC启动一个新线程的三种方法,有需要的朋友可以参考下。 第一种AfxBeginThread() 用AfxBeginThread()函数来创建一个新线程来执行任务,工作者线程的AfxBeginThread的原型如下: CWinThread* AfxBeginThread(AFX_THREADPROC pfnThreadProc,   LPVOID lParam,   int nPriority = THREAD_PRIORITY_NORMAL,   UINT nStackSize = 0,   DWORD dwCreateFlags = 0,   LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL   );//用于创建工作者线程 返回值: 成功时返回一个指向新线程的线程对象的指针,否则NULL。 pfnThreadProc : 线程的入口函数,声明一定要如下: UINT MyThreadFunction(LPVOID pParam),不能设置为NULL; pParam : 传递入线程的参数,注意它的类型为:LPVOID,所以我们可以传递一个结构体入线程. nPriority : 线程的优先级,一般设置为 0 .让它和主线程具有共同的优先级. nStackSize : 指定新创建的线程的栈的大小.如果为 0,新创建的线程具有和主线程一样的大小的栈 dwCreateFlags : 指定创建线程以后,线程有怎么样的标志.可以指定两个值: CREATE_SUSPENDED : 线程创建以后,会处于挂起状态,直到调用:ResumeThread 0 : 创建线程后就开始运行. lpSecurityAttrs : 指向一个 SECURITY_ATTRIBUTES 的结构体,用它来标志新创建线程的安全性.如果为 NULL, 那么新创建的线程就具有和主线程一样的安全性. 如果要在线程内结束线程,可以在线程内调用 AfxEndThread. 一般直接用AfxBeginThread(ThreadProc,this); 示例: UINT myproc(LPVOID lParam){CITTDlg *pWnd = (CITTDlg *)lParam; //将窗口指针赋给无类型指针pWnd->KMeansSegment(); //要执行的函数return 1;}void CITTDlg::KMeansSegment(){// 主要处理函数在这里写}void CITTDlg::OnKMeansSegment() //按钮点击执行{AfxBeginThread(myproc, (LPVOID)this);//启动新的线程} 注意,工作者线程的函数必须是全局函数或静态成员函数,不能是普通的成员函数。 第二种CreateThread()函数原型为:HANDLECreateThread( NULL, // 没有安全描述符 0, // 默认线程栈的大小 MyThreadProc, // 线程函数指针,即函数名 (LPVOID)&n, // 传递参数 NULL, // 没有附加属性 NULL // 不需要获得线程号码 ); CreatThread,它返回的是一个句柄;如果不需要再监视线程,则用CloseHandle()关闭线程句柄。 线程的函数必须定义为: DWORD WINAPI MyThreadProc(LPVOID pParameter); 下面演示多线程操作控件,点击一个Button然后运行一个线程,将字符串显示在CEdit控件里面; 示例: .h头文件struct hS {CString Tmp;CTestDlg *hWnd; };//定义全局结构体,用来传递自定义消息DWORD WINAPI ThreadProc(LPVOIDlpParam);//线程函数声明,全局函数public: CString chtmp; struct hS *hTmp;protected: HANDLE m_hThread;//线程句柄 CEdit m_Edit;.cpp实现文件//线程执行函数DWORD WINAPI ThreadProc(LPVOID lpParam){//在这里写处理函数struct hS *Tmp2;Tmp2 = (hS*)lpParam;// 操作: Tmp2->hWnd->m_Edit.SetWindowText( (LPTSTR)Tmp2->Tmp );}void CTestDlg::OnBnClickedButton1(){ hTmp->Tmp = chtmp; hTmp->hWnd = this;//关键是把this指针传进去 m_hThread =CreateThread(NULL,0,ThreadProc,hTmp,0,NULL);//创建新线程 CloseHandle(m_hThread );} 用CreateThread()函数创建线程将返回一个线程句柄,通过该句柄你可以控制和操作该线程,当你不用时可以一创建该线程后就关闭该句柄,有专门的函CloseHandle()。关闭句柄不代表关闭线程,只是你不能在外部控制该线程(比如,提前结束,更改优先级等)。在线程结束后,系统将自动清理线程资源,但并不自动关闭该句柄,所以线程结束后要记得关闭该句柄。 第三种_beginthread() 函数原型为:intptr_t _beginthread( void( *start_address )( void * ), //指向新线程调用的函数的起始地址 unsigned stack_size, //堆栈大小,设置0为系统默认值 void *arglist //传递给线程函数的参数,没有则为NULL ); 返回值: 假如成功,函数将会返回一个新线程的句柄,用户可以像这样声明一个句柄变量存储返回值:   HANDLE hStdOut = _beginthread( CheckKey, 0, NULL )。如果失败_beginthread将返回-1。所在库文件: #include 线程函数的定义: 对于_beginthread()创建的线程,其线程函数定义为: void ThreadPro(void * pArguments ); _beginthreadex()为_beginthread()的升级版。 总结:AfxBeginThreadMFC的全局函数,是对CreateThread的封装。 CreateThread是Win32 API函数,AfxBeginThread最终要调到CreateThread。而_beginthread是C的运行库函数。
/****************************************************************************************/ /* Compiler.cpp */ /* */ /* Author: Jim Mischel */ /* Description: Dialog and thread code for compiling maps with gbsplib */ /* */ /* The contents of this file are subject to the Genesis3D Public License */ /* Version 1.01 (the "License"); you may not use this file except in */ /* compliance with the License. You may obtain a copy of the License at */ /* http://www.genesis3d.com */ /* */ /* Software distributed under the License is distributed on an "AS IS" */ /* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See */ /* the License for the specific language governing rights and limitations */ /* under the License. */ /* */ /* The Original Code is Genesis3D, released March 25, 1999. */ /* Copyright (C) 1996-1999 Eclipse Entertainment, L.L.C. All Rights Reserved */ /* */ /****************************************************************************************/ #include "stdafx.h" #include "compiler.h" #pragma warning(disable : 4201 4214 4115 4514 4711) #include #include #pragma warning(default : 4201 4214 4115) #include #include #include #include "filepath.h" #include "consoletab.h" // for ConPrintf (yes, it's ugly) #include "util.h" static CWinThread *CompilerThread = NULL; static HWND hwndThreadParent = NULL; static geBoolean ThreadActive = GE_FALSE; static HINSTANCE GBSPHandle = NULL; static GBSP_FuncHook *GlobalFHook; static ofstream *CompileLog; CompilerErrorEnum Compiler_RunPreview ( char const *PreviewFilename, char const *MotionFilename, char const *GPreviewPath ) { assert (ThreadActive == GE_FALSE); char DestBspName[_MAX_PATH]; { // Verify the .BSP file exists... if (_access (PreviewFilename, 0) != 0) { return COMPILER_ERROR_NOBSP; } } // we're going to copy the preview file to the "levels" subdirectory // of the GPreviewPath directory... // // So, if the PreviewFilename is "C:\MyStuff\MyLevel.bsp", // and GPreviewPath is "C:\Editor\GPreview.exe", then the resulting // file name is "C:\Editor\levels\MyLevel.bsp" // { /* char PreviewDrive[_MAX_PATH]; char PreviewDir[_MAX_PATH]; char Name[_MAX_PATH]; char Ext[_MAX_PATH]; _splitpath (PreviewFilename, NULL, NULL, Name, Ext); _splitpath (GPreviewPath, PreviewDrive, PreviewDir, NULL, NULL); strcat (PreviewDir, "media\\levels\\"); _makepath (DestBspName, PreviewDrive, PreviewDir, Name, Ext); */ // make dest path same as source path strcpy(DestBspName, PreviewFilename); } // if source and destination are the same, then don't copy... if (stricmp (DestBspName, PreviewFilename) != 0) { if(!CopyFile (PreviewFilename, DestBspName, FALSE)) { int LastError; LastError = GetLastError(); if (LastError != ERROR_FILE_EXISTS) { ConPrintf("GPreviewPath: %s \n", GPreviewPath); ConPrintf("CopyFile (%s, %s)\nGetLastError()==%d\n", PreviewFilename, DestBspName, LastError); return COMPILER_ERROR_BSPCOPY; } } } { // copy the motion file if it exists char DestName[_MAX_PATH]; // check to see if the file exists FilePath_SetExt (DestBspName, ".mot", DestName); if (_access (MotionFilename, 0) == 0) // _access returns 0 on success...of course! { if (stricmp (MotionFilename, DestName) != 0) { if (!CopyFile (MotionFilename, DestName, FALSE)) { if(GetLastError() != ERROR_FILE_EXISTS) { ConPrintf ("%s", "Unable to copy the motion file.\n"); ConPrintf ("%s", "Continuing with preview.\n"); } } } } else { _unlink (DestName); } } { SHELLEXECUTEINFO shx; char Params[_MAX_PATH]; char DefaultDir[_MAX_PATH]; char NoExtName[_MAX_PATH]; FilePath_GetDriveAndDir (GPreviewPath, DefaultDir); FilePath_GetName (DestBspName, NoExtName); sprintf (Params, "-map %s", NoExtName); shx.fMask = 0; shx.hwnd = NULL; //(HWND)AfxGetMainWnd(); shx.lpVerb = NULL; shx.lpFile = GPreviewPath; shx.lpParameters= Params; shx.lpDirectory = DefaultDir; shx.nShow = SW_NORMAL; shx.hInstApp = NULL; shx.cbSize = sizeof(shx); ShellExecuteEx(&shx;); } return COMPILER_ERROR_NONE; } geBoolean Compiler_CancelCompile ( void ) { if (!ThreadActive) { return GE_FALSE; } return GlobalFHook->GBSP_Cancel (); } static CompilerErrorEnum Compiler_LoadCompilerDLL ( GBSP_FuncHook **ppFHook, HINSTANCE *pHandle, ERROR_CB ErrorCallbackFcn, PRINTF_CB PrintfCallbackFcn ) { GBSP_INIT *GBSP_Init; GBSP_Hook Hook; GBSP_FuncHook *FHook; assert (ppFHook != NULL); assert (pHandle != NULL); *ppFHook = NULL; Hook.Error = ErrorCallbackFcn; Hook.Printf = PrintfCallbackFcn; GBSPHandle = LoadLibrary("gbsplib.dll"); if (GBSPHandle == NULL) { PrintfCallbackFcn ("Compile Failed: Unable to load gbsplib.dll!\nGetLastError returned %d.\n", GetLastError ()); return COMPILER_ERROR_NODLL; } GBSP_Init =(GBSP_INIT*)GetProcAddress(GBSPHandle, "GBSP_Init"); if (GBSP_Init == NULL) { PrintfCallbackFcn ("%s", "Compile Failed: Couldn't initialize GBSP_Init, GBSPLib.Dll.\n."); FreeLibrary(GBSPHandle); return COMPILER_ERROR_MISSINGFUNC; } FHook = GBSP_Init (&Hook;); if (FHook == NULL) { PrintfCallbackFcn ("%s", "Compile Failed: GBSP_Init returned NULL Hook!, GBSPLib.Dll.\n."); FreeLibrary(GBSPHandle); return COMPILER_ERROR_MISSINGFUNC; } if(FHook->VersionMajor > GBSP_VERSION_MAJOR) { PrintfCallbackFcn ("%s", "Compile Failed: GBSP Version Incompatible, GBSPLib.Dll.\n."); FreeLibrary (GBSPHandle); return COMPILER_ERROR_MISSINGFUNC; } *ppFHook = FHook; *pHandle = GBSPHandle; return COMPILER_ERROR_NONE; } CompilerErrorEnum Compiler_Compile ( CompileParamsType const *pParams, ERROR_CB ErrorCallbackFcn, PRINTF_CB PrintfCallbackFcn ) { HINSTANCE GBSPHandle; CompilerErrorEnum CompileRslt; GBSP_RETVAL GbspRslt; char BspFilename[_MAX_PATH]; char MotionFilename[_MAX_PATH]; // load compiler DLL CompileRslt = Compiler_LoadCompilerDLL (&GlobalFHook;, &GBSPHandle;, ErrorCallbackFcn, PrintfCallbackFcn); if (CompileRslt == COMPILER_ERROR_NONE) { FilePath_SetExt (pParams->Filename, ".bsp", BspFilename); FilePath_SetExt (pParams->Filename, ".mot", MotionFilename); if (pParams->EntitiesOnly) { #if 1 #pragma message ("Should UpdateEntities return a GBSP_RETVAL?") if (GlobalFHook->GBSP_UpdateEntities ((char *)pParams->Filename, BspFilename)) { GbspRslt = GBSP_OK; } else { GbspRslt = GBSP_ERROR; } #else GbspRslt = GlobalFHook->GBSP_UpdateEntities ((char *)pParams->Filename, BspFilename); #endif switch (GbspRslt) { case GBSP_ERROR: PrintfCallbackFcn ("%s", "Compile Failed: GBSP_UpdateEntities returned an error. GBSPLib.Dll.\n"); CompileRslt = COMPILER_ERROR_BSPFAIL; break; case GBSP_OK : break; case GBSP_CANCEL : PrintfCallbackFcn ("%s", "UpdateEntities cancelled by user.\n"); CompileRslt = COMPILER_ERROR_USERCANCEL; break; default : assert (0); } } else if (pParams->RunBsp) { _unlink (MotionFilename); // gotta make sure this doesn't exist... GbspRslt = GlobalFHook->GBSP_CreateBSP ((char *)pParams->Filename, (BspParms *)&pParams;->Bsp); switch (GbspRslt) { case GBSP_ERROR : PrintfCallbackFcn ("%s", "Compile Failed: GBSP_CreateBSP encountered an error, GBSPLib.Dll.\n."); CompileRslt = COMPILER_ERROR_BSPFAIL; break; case GBSP_OK : //save as a bsp GbspRslt = GlobalFHook->GBSP_SaveGBSPFile(BspFilename); switch (GbspRslt) { case GBSP_ERROR : PrintfCallbackFcn ("Compile Failed: GBSP_SaveGBSPFile for file: %s, GBSPLib.Dll.\n.", BspFilename); CompileRslt = COMPILER_ERROR_BSPSAVE; break; case GBSP_CANCEL : PrintfCallbackFcn ("%s", "Save cancelled by user\n"); CompileRslt = COMPILER_ERROR_USERCANCEL; break; case GBSP_OK : break; default : assert (0); } break; case GBSP_CANCEL : PrintfCallbackFcn ("%s", "Compile cancelled by user\n"); CompileRslt = COMPILER_ERROR_USERCANCEL; break; default : assert (0); //?? } GlobalFHook->GBSP_FreeBSP(); } } if (CompileRslt == COMPILER_ERROR_NONE) { if(pParams->DoVis && !pParams->EntitiesOnly) { GbspRslt = GlobalFHook->GBSP_VisGBSPFile ((char *)BspFilename, (VisParms *)&pParams;->Vis); switch (GbspRslt) { case GBSP_ERROR : PrintfCallbackFcn ("Warning: GBSP_VisGBSPFile failed for file: %s, GBSPLib.Dll.\n.", BspFilename); break; case GBSP_CANCEL : PrintfCallbackFcn ("%s", "GBSP_VisGBPSFile cancelled by user\n"); CompileRslt = COMPILER_ERROR_USERCANCEL; break; case GBSP_OK : break; default : assert (0); } } } if (CompileRslt == COMPILER_ERROR_NONE) { if (pParams->DoLight) { /* The compiler has no flag that tells it not to do min lighting. So, if the min lighting flag is not on, we set the MinLight vector to all 0s. */ LightParms rad; rad = pParams->Light; if (!pParams->UseMinLight) { geVec3d_Set (&rad;.MinLight, 0.0f, 0.0f, 0.0f); } // If UseMinLight isn't on, then don't pass GbspRslt = GlobalFHook->GBSP_LightGBSPFile(BspFilename, &rad;); switch (GbspRslt) { case GBSP_ERROR : PrintfCallbackFcn ("Warning: GBSP_LightGBSPFile failed for file: %s, GBSPLib.Dll.\n", BspFilename); break; case GBSP_CANCEL : PrintfCallbackFcn ("%s", "GBSP_LightGBSPFile cancelled by user\n"); CompileRslt = COMPILER_ERROR_USERCANCEL; break; case GBSP_OK : break; default : assert (0); } } } // and free the DLL... if (GBSPHandle != NULL) { FreeLibrary (GBSPHandle); } return CompileRslt; } static void Compiler_NotifyApp ( char const *buf, int MsgId ) { #if 1 char *errmsg; errmsg = Util_Strdup (buf); if (errmsg != NULL) { ::PostMessage (hwndThreadParent, MsgId, COMPILER_PROCESSID, (LPARAM)errmsg); } #else ConPrintf ("%s", buf); #endif } static void Compiler_PrintfCallback ( char *format, ... ) { va_list argptr; char buf[32768]; //this is ... cautious va_start (argptr, format); vsprintf (buf, format, argptr); va_end (argptr); if (CompileLog) (*CompileLog) << buf; Compiler_NotifyApp (buf, WM_USER_COMPILE_MSG); } static void Compiler_ErrorCallback ( char *format, ... ) { va_list argptr; char buf[32768]; //this is ... cautious va_start (argptr, format); vsprintf (buf, format, argptr); va_end (argptr); if (CompileLog) (*CompileLog) << buf; Compiler_NotifyApp (buf, WM_USER_COMPILE_ERR); } static UINT Compiler_ThreadProc ( void *pParam ) { CompileParamsType CompileParams; CompilerErrorEnum CompileRslt; assert (pParam != NULL); assert (ThreadActive == GE_FALSE); ThreadActive = GE_TRUE; CompileParams = *((CompileParamsType *)pParam); char LogFilename[_MAX_PATH]; FilePath_SetExt(CompileParams.Filename, ".log", LogFilename); CompileLog = new ofstream(LogFilename, ofstream::out | ofstream::trunc); CompileRslt = Compiler_Compile (&CompileParams;, Compiler_ErrorCallback, Compiler_PrintfCallback); if (CompileRslt == COMPILER_ERROR_NONE) { Compiler_PrintfCallback ("%s", "------------------------------\n"); Compiler_PrintfCallback ("%s", "Compile successfully completed\n"); } if (CompileLog) { (*CompileLog).close(); delete CompileLog; } // notify parent that the compile has completed ::PostMessage (hwndThreadParent, WM_USER_COMPILE_DONE, COMPILER_PROCESSID, (LPARAM)CompileRslt); ThreadActive = GE_FALSE; return 0; } CompilerErrorEnum Compiler_StartThreadedCompile ( CompileParamsType const *pParams, HWND hwndNotify ) { CWinThread *Thread; assert (ThreadActive == GE_FALSE); hwndThreadParent = hwndNotify; Thread = AfxBeginThread ( Compiler_ThreadProc, // AFX_THREADPROC pfnThreadProc, (LPVOID)pParams, // LPVOID pParam, THREAD_PRIORITY_NORMAL, // int nPriority = THREAD_PRIORITY_NORMAL, 0, // UINT nStackSize = 0, 0, // DWORD dwCreateFlags = 0, NULL // LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL ); if (Thread != NULL) { CompilerThread = Thread; return COMPILER_ERROR_NONE; } else { return COMPILER_ERROR_THREAD; // couldn't spawn the thread } } geBoolean Compiler_CompileInProgress ( void ) { return ThreadActive; }

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧