标签:
因为需要些多线程的C++爬虫 之前弄得多线程没有使用互斥,然后出现一些问题就是,重复下载了网页......网上查了下 发现这块代码不多 所以我写个博客 分享给需要的人
编译环境VS2013+WIN8.1 或者codeblocks +win8.1 下面的代码是codeblocks下的,变化一处就可以放vs 见注释
代码参考了这里:http://bbs.csdn.net/topics/370051110
// MulThread.cpp : 定义控制台应用程序的入口点。 // #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 ); DWORD 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");//如果是VS2013 hMutex = CreateMutex(NULL, TRUE, L"queue"); if (hMutex) { if (ERROR_ALREADY_EXISTS == GetLastError()) { cout << "only one 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++ 多线程+使用互斥资源(购票程序为例)
标签:
原文地址:http://blog.csdn.net/u011026968/article/details/45047401