标签:
我第一个多线程程序,先贴代码,明天再来详细的写:
// 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); //MessageBox(NULL, TEXT("这是对话框"), TEXT("你好"), MB_ICONINFORMATION | MB_YESNO); 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; }
标签:
原文地址:http://www.cnblogs.com/qiaozhoulin/p/4562241.html