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;}
结果:
阅读全文
0 0
- C多线程编程-互斥量
- c语言多线程编程
- C#:多线程编程探索
- linux c 多线程编程
- Linux C多线程编程
- C/C++ 多线程编程
- C语言多线程编程
- Linux C 多线程编程
- linux-C编程-多线程
- Linux c 多线程编程
- C多线程编程
- 【C++】:C++多线程编程
- Linux C多线程编程
- C/C++多线程编程
- Linux C 多线程编程
- [Linux C编程]多线程
- C多线程编程
- [Linux C编程]多线程编程
- android上传多图片使用FileBody
- (转) dubbo的初步了解
- Eclipse安装反编译插件
- Linux进程间通信——使用命名管道
- DBUtils 查询操作的九种结果集处理
- C++ 多线程编程 互斥量
- spring JavaMail 邮件发送
- python with as的用法
- 远程控制服务器相关/文件处理相关的一些linux(Ubuntu)命令
- 发送短信-java
- selenium对浏览器的操作
- 当creator遇上protobufjs|结晶
- Redis
- Linux 文件锁