近期自学Windows多线程知识,贴出例程。
1 #include <iostream> 2 #include <windows.h> 3 #include <process.h> 4 using namespace std; 5 HANDLE hMutex = NULL;//互斥量 6 HANDLE mutex = NULL; 7 8 unsigned WINAPI Fun1(PVOID lpParamter) 9 { 10 WaitForSingleObject(mutex, INFINITE); 11 for (int i = 0; i < 3; i++) 12 cout << "A Thread Fun 1 Display!"<<endl; 13 Sleep(200); 14 ReleaseMutex(mutex); 15 return 0L; 16 } 17 18 19 void main() 20 { 21 HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, Fun1, NULL, 0, NULL);//较CreateThread更加安全 22 //HANDLE hThread = CreateThread(NULL, 0, Fun1, NULL, 0, NULL); 23 CloseHandle(hThread); 24 //_endthreadex((unsigned)hThread);//较CloseHandle更加安全 25 mutex = CreateMutex(NULL,false,"Ohye"); 26 27 for (int i = 0; i < 3; i++){ 28 WaitForSingleObject(mutex, INFINITE); 29 cout << "Main Thread Display!" << endl; 30 Sleep(500); 31 ReleaseMutex(mutex); 32 } 33 34 system("pause"); 35 }