第一個 API :創建一個線程
CreateThread()
The CreateThread function creates a thread to execute within the address space of the calling process.
HANDLE CreateThread(
??? LPSECURITY_ATTRIBUTES lpThreadAttributes,??????????????? // pointer to thread security attributes?
??? DWORD dwStackSize,??????????????? // initial thread stack size, in bytes
??? LPTHREAD_START_ROUTINE lpStartAddress,? // pointer to thread function
??? LPVOID lpParameter,// argument for new thread
??? DWORD dwCreationFlags,??????? // creation flags
??? LPDWORD lpThreadId ?????????????? // pointer to returned thread identifier
?? );
Return Values
If the function succeeds, the return value is a handle to the new thread.
If the function fails, the return value is NULL. To get extended error information, call etLastError.
Example1: 創建一個線程
#include
<windows.h>
DWORD
WINAPI
threadFunc (LPVOIDpArg)
{
??????
return 0;
}
main
()
{?????
??????
HANDLE
hThread;
??????
hThread = CreateThread (NULL, 0, threadFunc, NULL, 0, NULL );
??????
return 0;
}
上面這段代碼有一個小問題,那就是 threadFunc 有可能不會被執行到就結束了!要保證 threadFunc 肯定被執行(也就是等線程退出),在 CreateThread 后加一行代碼:
???????????????
WaitForMultipleObjects
(1, &hThread, TRUE, INFINITE);
第二個
API
:等待線程返回
WaitForMultipleObjects
The WaitForMultipleObjects function returns when one of the following occurs:
Either any one or all of the specified objects are in the signaled state.
The time-out interval elapses.
DWORD WaitForMultipleObjects(
??? DWORD nCount,????????? // number of handles in the object handle array
??? CONST HANDLE *lpHandles,?? // pointer to the object-handle array
??? BOOL bWaitAll,???????????? // wait flag
??? DWORD dwMilliseconds ????????? // time-out interval in milliseconds
?? );
If dwMilliseconds is INFINITE, the function's time-out interval never elapses.
Example2: 四個線程一起運行
#include
<Windows.h>
#include
<stdio.h>
const
int
numThreads = 4;
DWORD
WINAPI
threadFunc(LPVOIDpArg)
{
??????
int *p = (int *)pArg;
??????
int
num = *p;
??????
printf("threadFunc...%d...\n", num);
??????
return 0;
}
int
main()
{
??????
HANDLE
hThread[numThreads];
??????
int
threadNum[numThreads];
??????
for(inti=0; i<numThreads; i++)
?????? {
?????????????
threadNum[i] = i;
?????????????
hThread[i] = CreateThread(NULL, 0, threadFunc, &threadNum[i], 0, NULL);
?????? }
??????
??????
WaitForMultipleObjects(numThreads, hThread, TRUE, INFINITE);
??????
return 0;
}