WIN32多线程编程( CreateThread 版本)
一、线程的创建、运行与结束
示例代码:
#include <stdio.h>
#include <windows.h>
DWORD WINAPI ThreadFun(LPVOID pM)
{
printf("%s\n", pM);
return 0;
}
int main()
{
printf("main thread\n");
HANDLE handle1 = CreateThread(NULL, 0, ThreadFun, "Thread one", 0, NULL);
HANDLE handle2 = CreateThread(NULL, 0, ThreadFun, "Thread two", 0, NULL);
DWORD exitCode1 = 0, exitCode2 = 0;
while(1){
GetExitCodeThread(handle1, &exitCode1);
GetExitCodeThread(handle2, &exitCode2);
if(exitCode1 != STILL_ACTIVE && exitCode2 != STILL_ACTIVE)
break;
}
CloseHandle(handle1);
CloseHandle(handle2);
system("PAUSE");
return 0;
}
解析:
1、CreateThread 包含在 windows.h 头文件中;
2、线程函数为 DWORD WINAPI (*ThreadFun)(LPVOID pM ) 类型,一个线程函数可以被多个线程调用;
3、线程创建函数为CreateThread( ),其具体参数如下: