博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
boost库在工作(19)线程之四
阅读量:4162 次
发布时间:2019-05-26

本文共 1247 字,大约阅读时间需要 4 分钟。

从前面也看到使用锁boost::mutex时,如果不小心就会死锁,这样要费心费力去维护这样的代码,在boost库里提供同一个函数递归调用时使用的锁boost::recursive_mutex,当同一个线程调用时,碰到相同已经上锁的锁时,还可以继续往下执行。这时就不用担心同一个线程调用不同的函数时造成死锁了。在前面的例子死锁的代码,当换成这个锁之后,就不会再有死锁了,代码如下:
// boost_012.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include 
#include
#include
//全局锁。boost::recursive_mutex g_mutexAll;//递归锁不会死锁void First(void){ std::cout << "First In" << std::endl; boost::lock_guard
autoLock(g_mutexAll); std::cout << "First Out" << std::endl;}void Second(void){ std::cout << "Second In" << std::endl; boost::lock_guard
autoLock(g_mutexAll); std::cout << "Second Out" << std::endl; //这里递归访问同一个锁,使用递归锁后不会死锁。 First();}//线程组运行的函数void Run(int nVal){ // int nTemp = nVal * nVal; //下面输出需要加锁,不能多个线程共享输出。 static boost::mutex mutexCout; boost::lock_guard
autoLock(mutexCout); std::cout << "thread Run: [" << nVal << "] " << nTemp << std::endl; // Second();}int _tmain(int argc, _TCHAR* argv[]){ //定义一个线程组对象。 boost::thread_group threadGroup; //设置最大的线程个数。 const int nMaxCount = 5; //循环地创建N个线程。 for (int i = 0; i < nMaxCount; ++i) { threadGroup.create_thread(boost::bind(Run, i)); } //等所有线程退出。 threadGroup.join_all(); system("PAUSE"); return 0;}

转载地址:http://qaixi.baihongyu.com/

你可能感兴趣的文章
Visual Tracking Using Attention-Modulated Disintegration and Integration
查看>>
Action-Decision Networks for Visual Tracking with Deep Reinforcement Learning
查看>>
Multiple Object Tracking with High Performance Detection and Appearance Feature
查看>>
深度学习入门(上)-第一章 必备基础知识点
查看>>
ubuntu unzip解压时提示错误 解决方法
查看>>
sprintf函数的说明
查看>>
BOOST_TYPEOF和BOOST_AUTO 作用
查看>>
随机森林概述
查看>>
2011十大战略技术
查看>>
大学应该学的软件知识
查看>>
腾讯与360战争背后的云计算阴影
查看>>
腾讯看了会沉默,360看了会流泪
查看>>
李开复:移动互联网机会最大 微博会现最大赢家
查看>>
2006年的IT十大战略技术
查看>>
操作系统介绍
查看>>
Desktop Linux: The Dream Is Dead
查看>>
我的9年IT路
查看>>
任正非:让用户像用电一样享受云计算
查看>>
学习技术的几个境界
查看>>
计算机世界:免费的代价
查看>>