1 #include<Windows.h> 2 #include<iostream> 3 4 using namespace std; 5 6 /*1、在启动一个线程之前,必须为线程编写一个全局的线程函数, 7 * 这个线程函数接受一个32位的LPVOID(没有类型的指针)作为参数,返回一个DWORD 8 *这里建了两个全局的线程函数ThreadFuncFirst,ThreadFuncSecond*/ 9 DWORD WINAPI ThreadFuncFirst(LPVOID param) { //DWORD:32位无符号整型数据(DWORD32), VOID:无类型,相当于标准C语言中的void,LPVOID无类型指针 10 int iCount = 100; 11 //2、 在线程处理代码部分通常包括一个死循环,该循环中先等待某事情的发生,再处理相关的工作 12 while (iCount--) { 13 cout << "ThreadFuncFirst:" << iCount<<endl; 14 } 15 return 0; 16 } 17 18 DWORD WINAPI ThreadFuncSecond(LPVOID param) 19 { 20 int iCount = 150; 21 while (iCount--) { 22 cout << "ThreadFuncSecond:" << iCount<<endl; 23 } 24 return 0; 25 } 26 27 int main() { 28 DWORD dwThreadID = 0; 29 //3、创建两个线程handleFirst,handleSecond,返回窗口的句柄HANDLE 30 HANDLE handleFirst = CreateThread(NULL, 0, ThreadFuncFirst, 0, 0, &dwThreadID); 31 if (!handleFirst) 32 { 33 cout << "create thread 1 error:" << endl; 34 } 35 HANDLE handleSecond = CreateThread(NULL, 0, ThreadFuncSecond, 0, 0, &dwThreadID); 36 if (!handleSecond) 37 { 38 cout << "create thread 2 error:" << endl; 39 } 40 41 //HANDLE arrayHandle[] = {handleFirst, handleSecond}; 42 //WaitForMultipleObjects(2, arrayHandle, TRUE, INFINITE); 43 44 //4、等待线程返回,用sleep()就太LOW了 45 WaitForSingleObject(handleFirst, INFINITE); 46 WaitForSingleObject(handleSecond, INFINITE); 47 CloseHandle(handleFirst);//句柄默认值2 这里减1,线程函数执行完后释放资源。 48 CloseHandle(handleSecond); 49 50 return 0; 51 }
建议开始之前详细阅读和理解我转发的《多线程学习:win32多线程编程基本概念》https://www.cnblogs.com/chaoyingLi/p/11236070.html