”CreateThread()之后又马上CloseHandle()的问题“ 及 一些注意点

来源:互联网 发布:三维试衣软件哪个好 编辑:程序博客网 时间:2024/06/01 09:06
void main(){// Create worker threadsfor( i=0; i < 2; i++ ){aThread[i] = CreateThread( NULL,0,(LPTHREAD_START_ROUTINE) WriteToDatabase, &i,       // 注意:这里是给线程回调函数传参数0,          &ThreadID);}}DWORD WINAPI WriteToDatabase( LPVOID lpParam ){ // 注意:这里不会得到0,1, 而是总是得到2。。// 因为主函数那里已经不断的循环,最终i的值已经被修改为2 后,这个// 线程函数才执行起来。  所以,诸如此类问题需要多多注意。int i = *(int*)lpParam; return TRUE; }



此外,CreateThread()之后又马上CloseHandle()的问题, 可以参考http://blog.csdn.net/kofandlizi/article/details/6458011。

// 本段代码摘自 MSDN, 随便找WaitForSingleObject 函数就能找到这段代码了。// 这里引用,目的在于做学习笔记。。#include "stdafx.h"#include <windows.h>#include <stdio.h>#define THREADCOUNT 2HANDLE ghMutex; DWORD WINAPI WriteToDatabase( LPVOID );void main(){HANDLE aThread[THREADCOUNT];DWORD ThreadID;int i;// Create a mutex with no initial ownerghMutex = CreateMutex( NULL,              // default security attributesFALSE,             // initially not ownedNULL);             // unnamed mutexif (ghMutex == NULL) {printf("CreateMutex error: %d\n", GetLastError());return;}// Create worker threadsfor( i=0; i < THREADCOUNT; i++ ){aThread[i] = CreateThread( NULL,       // default security attributes0,          // default stack size(LPTHREAD_START_ROUTINE) WriteToDatabase, NULL,       // no thread function arguments0,          // default creation flags&ThreadID); // receive thread identifierif( aThread[i] == NULL ){printf("CreateThread error: %d\n", GetLastError());return;}}// 注意,CloseHandle 调用不能在这句前,因为这句都还需要 线程句柄呢。//// MSDN 有如下描述:// Return Value// If the function succeeds, the return value is a handle to the new thread. // When you have finished using the handle, close it by calling the CloseHandle function. // 所以如果不是因为 WaitForMultipleObjects 还需要用到线程句柄的话, 你在其他工程代码中看到// 类似如下代码(即调用完CreateThread后马上调用CloseHandle)也不会感到奇怪了。。// HANDLE hThread = CreateThread(NULL, 1024 * 1024 * 20, ReadFromDeviceThreadProc, this, 0, &dwThreadId);// if (hThread != NULL)// {// CloseHandle(hThread);// }//WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE); // Wait for all threads to terminate// Close thread and mutex handlesfor( i=0; i < THREADCOUNT; i++ )CloseHandle(aThread[i]);CloseHandle(ghMutex);}DWORD WINAPI WriteToDatabase( LPVOID lpParam ){ DWORD dwCount=0, dwWaitResult; // Request ownership of mutex.while( dwCount < 20 ){ dwWaitResult = WaitForSingleObject( ghMutex,    // handle to mutexINFINITE);  // no time-out intervalswitch (dwWaitResult) {// The thread got ownership of the mutexcase WAIT_OBJECT_0: __try { // TODO: Write to the databaseprintf("Thread %d writing to database...\n", GetCurrentThreadId());dwCount++;} __finally { // Release ownership of the mutex objectif (! ReleaseMutex(ghMutex)) { // Deal with error.} } break; // The thread got ownership of an abandoned mutexcase WAIT_ABANDONED: return FALSE; }}return TRUE; }


0 0
原创粉丝点击