编写的多线程程序,是根据孙鑫的视频讲解写的,这个代码重点在于线程同步,需要注意的是线程的时间片的划分,如果主线程的时间片一直在运行的话,程序是不会进入子线程的。
// MultiThread.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<windows.h> #include<iostream> using namespace std; DWORD WINAPI Thread1(LPVOID lpParamenter); DWORD WINAPI Thread2(LPVOID lpParamenter); int ticket = 100; HANDLE hMutex; int main(int argc, _TCHAR* argv[]) { HANDLE hThread1, hThread2; hThread1 = CreateThread(NULL, 0, Thread1, NULL, 0, NULL); hThread2 = CreateThread(NULL, 0, Thread2, NULL, 0, NULL); CloseHandle(hThread1); CloseHandle(hThread2); hMutex=CreateMutex(NULL,false,NULL); Sleep(1000); return 0; } DWORD WINAPI Thread1(LPVOID lpParamenter) { while (true) { WaitForSingleObject(hMutex, INFINITE); if (ticket > 0) { Sleep(1); cout << "Thread1 sell ticket:" << ticket-- << endl; } else { break; } ReleaseMutex(hMutex); } return 0; } DWORD WINAPI Thread2(LPVOID lpParamenter) { while (true) { WaitForSingleObject(hMutex, INFINITE); if (ticket > 0) { Sleep(1); cout << "Thread2 sell ticket:" << ticket-- << endl; } else { break; } ReleaseMutex(hMutex); } return 0; }