WIN 多線程API
一 簡(jiǎn)單實(shí)例
比較簡(jiǎn)單的代碼,創(chuàng)建10個(gè)線程,其中使第4個(gè)線程在一創(chuàng)建就掛起,等到其他的線程執(zhí)行的差不多的時(shí)候再使第4個(gè)線程恢復(fù)執(zhí)行。
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

#define THREAD_NUM 10

DWORD WINAPI PrintThreads (LPVOID);

int main ()


{
HANDLE hThread[THREAD_NUM];
DWORD dwThreadID[THREAD_NUM];

for (int i=0; i<THREAD_NUM; ++i)

{
int isStartImmediate = 0;
if(3 == i)
isStartImmediate = CREATE_SUSPENDED;
hThread[i]=CreateThread(NULL, // security attributes that should be applied to the new thread,
// this is for NT. Use NULL to get the default security attributes. Use NULL for win95
0, // default size of 1MB can be passed by passing zero.
PrintThreads, // function name:address of the function where the new thread starts.
(LPVOID)i, // parameter(void pointer): pointer to the 32 bit parameter that will be passed into the thread
isStartImmediate, // flags to control the creation of the thread. Passing zero starts the thread immediately.
// Passing CREATE_SUSPENDED suspends the thread until the ResumeThread( ) function is called.
&dwThreadID[i] // pointer to a 32-bit variable that receives the thread identifier.
);
if (hThread[i])

{
printf ("Thread launched successfully\n");
}
}
printf("Start sleep 100, and let other thread excute\n");
Sleep (100);

printf("Start sleep 100, and thread 3 excute\n");
ResumeThread(hThread[3]);
Sleep(100);

for(int i = 0; i<THREAD_NUM; ++i)

{
if (hThread[i])

{
CloseHandle(hThread[i]); // You need to use this to release kernel objects when you are done using them.
// If a process exits without closing the thread handle,
// the operating system drops the reference counts for those objects.
// But if a process frequently creates threads without closing the handles,
// there could be hundreds of thread kernel objects lying around and these resource leaks can have a big hit on performance.
}
}
return (0);
}

//function PrintThreads
DWORD WINAPI PrintThreads (LPVOID num)


{
for (int i=0; i<10; i++)
printf ("Thread Number is %d%d%d\n", num,num,num);
return 0;
}
二 其他基本API的說(shuō)明
CreateThread() 調(diào)用成功返回句柄和一個(gè)id。
CloseHandle() 關(guān)閉一個(gè)打開(kāi)的對(duì)象句柄,該對(duì)象句柄可以是線程句柄,也可以是進(jìn)程、信號(hào)量等其他內(nèi)核對(duì)象的句柄.
SuspendThread(HANDLE) 允許開(kāi)發(fā)人員將HANDLE指定的線程掛起,如果要掛起的線程占有共享資源,則可能導(dǎo)致死鎖。
ResumeThread(HANDLE) 恢復(fù)指定的線程。
TerminateThread() 立即終止線程的工作,不做任何清理工作。
ExitThread() 線程函數(shù)返回時(shí)回調(diào)用次函數(shù),所以一般我們不去顯示的調(diào)用。
ExitThread是推薦使用的結(jié)束一個(gè)線程的方法,當(dāng)調(diào)用該函數(shù)時(shí),當(dāng)前線程的棧被釋放,然后線程終止,相對(duì)于TerminateThread函數(shù)來(lái)說(shuō),這樣做能夠更好地完成附加在該線程上的DLL的清除工作. 但是ExitThread()會(huì)導(dǎo)致線程在清處構(gòu)造器/自動(dòng)變量之前就終止,所以我們最好不要顯示的調(diào)用ExitThread()。