C++11实现多线程 互斥锁与资源竞争问题
来源:互联网 发布:中国帝国 知乎 编辑:程序博客网 时间:2024/06/10 11:21
//MThread.h
#include <iostream>
#include <thread>#include <mutex>
class MThread
{
public:
MThread(int x);
~MThread();
static void run(int x);
std::thread threads;
private:
int x;
};
//MThread.cpp
#include "MThread.h"
#include <iostream>
#include <Windows.h>
std::mutex mutex;
MThread::MThread(int x)
{
this->x = x;
this->threads = std::thread(run, this->x);
}
MThread::~MThread()
{
}
void MThread::run(int x)
{
for(int i = 0; i < 20; i++;)
{
if(mutex.try_lock())
{
std::cout << "线程" << x << "第" << i + 1 << "次执行" << std::endl ;
mutex.unlock();
}
}
}
//main.cpp
#include <iostream>
#include <thread>
#include <mutex>
#include "MThread.h"
int main (int argc, const char* argv[])
{
MThread * mt[3];
for(int i = 0; i < 3; i++)
{
mt[i] = new MThread(i + 1);
}
for(auto &th : mt)
th->threads.join();
return 0;
}
如图所示,线程2和3的输出并没有被调用。仔细观察程序就能发现,不是线程2和3没有运行,而是当线程2和3进行try_lock()的时候,没有成功,但是仍然进行了i++操作,所以如果把MThread.cpp中的run方法改成
void MThread::run(int x)
{
for(int i = 0; i < 20; )
{
if(mutex.try_lock())
{
std::cout << "线程" << x << "第" << i + 1 << "次执行" << std::endl ;
mutex.unlock();
i++;
}
}
}
线程2和3的运行结果就可以输出了,如图所示
- C++11实现多线程 互斥锁与资源竞争问题
- 多线程竞争资源问题
- C++——多线程编程(二)std::mutex 线程同步、解决资源竞争问题
- 多线程数据竞争问题
- 多线程竞争问题分析
- 资源竞争与并发控制
- Java多线程、并发时使用Synchronized(同步锁)解决资源竞争问题
- 多进程竞争资源----哲学家就餐问题
- java资源竞争问题(线程互斥)
- java资源竞争问题(线程互斥)
- Linux C 线程与竞争
- UIActionSheet与HUD的window资源竞争
- 资源竞争
- 多线程竞争
- 11java 王少飞-多线程临界资源问题
- C++多线程编程学习一 [关于数据竞争问题]
- C++多线程编程一 [关于数据竞争问题]
- 多线程学习之数据竞争与互斥对象
- Android开发:界面布局的基本使用
- IO复用 select Demo
- poj 1012 约瑟夫问题
- C++primer(第四版)复习笔记—第一篇:基本语言
- CV 资源汇总
- C++11实现多线程 互斥锁与资源竞争问题
- text和checkbox只读属性的设置
- (转)数据库范式(1NF 2NF 3NF BCNF)详解一
- YARN的 Resource Manager的作用
- 设备驱动程序通知应用程序的几种方法
- 笔试题(1)
- MFC 使用JSONCPP
- 现代谜题
- python-shell-MySQL