C++ 多线程编程 互斥量

来源:互联网 发布:淘宝win10激活码重装 编辑:程序博客网 时间:2024/05/21 09:47

Win10下多线程中访问公共变量时,可使用mutex类来做,头文件为mutex,实例(VS2013):

#include <iostream>#include <thread>#include <Windows.h>#include <mutex>using namespace std;mutex mu;  //线程互斥对象int totalNum = 100;void thread01(){while (totalNum > 0){mu.lock(); //同步数据锁cout << totalNum << endl;totalNum--;Sleep(100);mu.unlock();  //解除锁定}}void thread02(){while (totalNum > 0){mu.lock();cout << totalNum << endl;totalNum--;Sleep(100);mu.unlock();}}int main(){thread task01(thread01);thread task02(thread02);task01.detach();task02.detach();system("pause");}


输出:



若不加互斥,如下屏蔽:

#include <iostream>#include <thread>#include <Windows.h>#include <mutex>using namespace std;mutex mu;  //线程互斥对象int totalNum = 100;void thread01(){while (totalNum > 0){//mu.lock(); //同步数据锁cout << totalNum << endl;totalNum--;Sleep(100);//mu.unlock();  //解除锁定}}void thread02(){while (totalNum > 0){//mu.lock();cout << totalNum << endl;totalNum--;Sleep(100);//mu.unlock();}}int main(){thread task01(thread01);thread task02(thread02);task01.detach();task02.detach();system("pause");}


可看到,有丢失,有重复的现象出现:



参考网址


还可使用如下方法,用WaitForSingleObject和ReleaseMutex:

#include <iostream>   #include <windows.h>   using namespace std;DWORD bRet;HANDLE hMutex = NULL;DWORD WINAPI Fun(LPVOID lpParamter){for (int i = 0; i < 10; i++){bRet = WaitForSingleObject(hMutex, INFINITE);if (bRet == WAIT_OBJECT_0){//printf("Process is signaled...:%d\n", GetLastError());}else if (bRet == WAIT_TIMEOUT){//printf("Time out...:%d\n", GetLastError());}else if (bRet == WAIT_FAILED){//printf("Invalid process handle...:%d\n", GetLastError());}cout << "A    Thread Display!" << endl;ReleaseMutex(hMutex);Sleep(100);}return 0L;}int main(){hMutex = CreateMutex(NULL, FALSE, NULL);HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);CloseHandle(hThread);for (int i = 0; i < 10; i++){WaitForSingleObject(hMutex, INFINITE);cout << "Main Thread Display!" << endl;ReleaseMutex(hMutex);Sleep(200);}system("PAUSE");return 0;}

结果:


原创粉丝点击