Because of the need for some multi-threaded C + + crawler before the multithreading did not use mutex, and then there are some problems is, repeatedly downloaded the page ... I found this piece of code on the Internet, so I wrote a blog to share it with people in need.
Compile the Environment vs2013+win8.1 or codeblocks +win8.1 The following code is codeblocks, change one place can put vs see note
The code references here: http://bbs.csdn.net/topics/370051110
MulThread.cpp: Defines the entry point of the console application. #include <iostream> #include <windows.h> #include <process.h> #include <fstream> #include <stdlib.h> #include <cstdio>using namespace Std;dword WINAPI fun1proc (LPVOID lpparameter//thread data);D wo RD WINAPI Fun2proc (LPVOID lpparameter//thread data); int index = 0;int tickets = 100; HANDLE Hmutex;int Main () {HANDLE hThread1; HANDLE hthread2;hthread1 = CreateThread (null, 0, fun1proc, NULL, 0, NULL); hThread2 = CreateThread (null, 0, fun2proc, NULL, 0, NULL); CloseHandle (HTHREAD1); CloseHandle (hThread2);//Hmutex=createmutex (null,true,null); Hmutex = CreateMutex (NULL, TRUE, "queue");//If it is VS2013 Hmutex = CreateMutex (NULL, TRUE, L "queue"), if (Hmutex) {if (error_already_exists = = GetLastError ()) {cout << "only on E instance can run! "<< Endl;return 0;}} WaitForSingleObject (Hmutex, INFINITE); ReleaseMutex (Hmutex); ReleaseMutex (Hmutex);//sleep (4000); System ("pause"); return 0;} DWORD WINAPI Fun1proc (lpvoid lpparameter/tHread data) {while (TRUE) {WaitForSingleObject (hmutex,infinite); if (tickets>0) {Sleep (1); cout<< "Thread1 Sell ticket:" <<tickets--<<endl; } else break; ReleaseMutex (Hmutex);} return 0;} DWORD WINAPI Fun2proc (LPVOID lpparameter//thread data) {while (TRUE) {WaitForSingleObject (hmutex,infinite); if (tickets>0) {Sleep (1); cout<< "Thread2 Sell ticket:" <<tickets--<<endl; } else break; ReleaseMutex (Hmutex);} return 0;}
Windows C + + multithreading + using mutually exclusive resources (ticket purchase procedure for example)