void main()
{
// Create worker threads
for( 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 2
HANDLE ghMutex;
DWORD WINAPI WriteToDatabase( LPVOID );
void main()
{
HANDLE aThread[THREADCOUNT];
DWORD ThreadID;
int i;
// Create a mutex with no initial owner
ghMutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
NULL); // unnamed mutex
if (ghMutex == NULL)
{
printf("CreateMutex error: %d\n", GetLastError());
return;
}
// Create worker threads
for( i=0; i < THREADCOUNT; i++ )
{
aThread[i] = CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE) WriteToDatabase,
NULL, // no thread function arguments
0, // default creation flags
&ThreadID); // receive thread identifier
if( 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 handles
for( 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 mutex
INFINITE); // no time-out interval
switch (dwWaitResult)
{
// The thread got ownership of the mutex
case WAIT_OBJECT_0:
__try {
// TODO: Write to the database
printf("Thread %d writing to database...\n",
GetCurrentThreadId());
dwCount++;
}
__finally {
// Release ownership of the mutex object
if (! ReleaseMutex(ghMutex))
{
// Deal with error.
}
}
break;
// The thread got ownership of an abandoned mutex
case WAIT_ABANDONED:
return FALSE;
}
}
return TRUE;
}