一 简单实例
比较简单的代码,创建10个线程,其中使第4个线程在一创建就挂起,等到其他的线程执行的差不多的时候再使第4个线程恢复执行。
- #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,
- 0,
- PrintThreads,
- (LPVOID)i,
- isStartImmediate,
- &dwThreadID[i]);
- 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])
- {
- // 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.
- CloseHandle(hThread[i]);
- }
- }
- 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;
- }
MSDN中CreateThread原型:
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
SIZE_T dwStackSize, // initial stack size
LPTHREAD_START_ROUTINE lpStartAddress, // thread function
LPVOID lpParameter, // thread argument
DWORD dwCreationFlags, // creation option
LPDWORD lpThreadId // thread identifier
);