本来是想测试一下在多线程环境下printf多次输出的情况,验证一下自己的想法,结果自己的测试程序貌似有问题,测试不出来.....先记下如何创建线程,减少烦人的编译错误先
/* ----------------------------------------------------------------------------------- 这个是用_beginthreadex创建线程的。 ----------------------------------------------------------------------------------- */ //#define _WIN32_WINNT 0x0400 #include<windowsx.h>//里面竟然不包括windows.h #include<windows.h> //为什么不支持Windowsx.h #include<stdio.h> #include<process.h> typedef unsigned (__stdcall *PTHREAD_START ) (void *) ; #define chBEGINTHREADEX(psa,cbStackSize,pfnStartAddr, \ pvParam,dwCreateFlags,pdwThreadId) \ ((HANDLE)_beginthreadex( \ (void*)(psa), \ (unsigned)(cbStackSize), \ (PTHREAD_START) (pfnStartAddr), \ (void *)(pvParam), \ (unsigned)(dwCreateFlags), \ (unsigned *)(pdwThreadId))) DWORD WINAPI ClientThread(PVOID pvParam) ; int main(void) { DWORD nThreadNum ; HANDLE hThread[5] ; for(int i = 0 ; i < 5 ; i++) { hThread[i] = chBEGINTHREADEX(NULL,0,ClientThread,i+1,0,&nThreadNum) ; } WaitForMultipleObjects(5,hThread,TRUE,INFINITE) ; for(int j = 0 ; j < 5 ; j++) { CloseHandle(hThread[j]) ; } printf("程序结束\n") ; return 0 ; } DWORD WINAPI ClientThread(PVOID pvParam) { int nThreadNum = PtrToUlong(pvParam) ; for(int i = 0 ; i < 10000 ; i++) { printf("第%d线程第%d循环\n",nThreadNum,i+1) ; Sleep(5000) ; } return 0 ; }
/* -------------------------------------------------------------------------------- 这个是用CreateThread创建的线程 -------------------------------------------------------------------------------- */ #include<windows.h> #include<stdio.h> DWORD WINAPI ThreadFun(PVOID pvParam) ; int main(void) { DWORD dwThreadId = 0 ; int nNum = 0 ; int i = 0 ; nNum = 2 ; CreateThread(NULL,0,ThreadFun,(PVOID)&nNum,0,&dwThreadId) ; Sleep(100) ; for(i = 0 ; i < 10000 ; ++i) { printf("ThreadNum : %d\n",1) ; Sleep(1000) ; } return 0 ; } DWORD WINAPI ThreadFun(PVOID pvParam) { DWORD i = 0 ; DWORD dwNum = *((int *)pvParam) ; for(i = 0 ; i < 10000 ; ++i) { printf("ThreadNum : %d\n",dwNum) ; Sleep(1000) ; } return 0 ; }