zoukankan      html  css  js  c++  java
  • boost库在工作(20)线程之五

    通过上面的学习,基本上就可以使用线程了,但怎么样让线程运行类里的成员函数呢?以便封装得更方便使用了。接着下来,就看这个例子,如下:

    // boost_013.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <boost/thread.hpp>
    #include <boost/bind.hpp>
    #include <boost/thread/mutex.hpp>
    
    //封装线程组运行的类, 并且演示使用类成员函数作为线程组运行函数
    //软件开发人员: 蔡军生  2013-04-05
    //QQ: 9073204
    class CThreadBase
    {
    public:
    	void Start(int nMaxCount)
    	{		
    		//循环地创建N个线程。
    		for (int i = 0; i < nMaxCount; ++i)
    		{
    			m_threadGroup.create_thread(boost::bind(&CThreadBase::Run, this, i));
    		}
    	}
    
    	void Stop(void)
    	{
    		//等所有线程退出。
    		m_threadGroup.join_all();
    	}
    
    	virtual void Run(int nVal)
    	{
    		//
    		int nTemp = nVal * nVal;
    
    		//下面输出需要加锁,不能多个线程共享输出。
    		static boost::mutex mutexCout;
    		boost::lock_guard<boost::mutex> autoLock(mutexCout);
    		std::cout << "thread Run: [" << nVal << "] " << nTemp << std::endl;
    	}
    private:
    	//定义一个线程组对象。
    	boost::thread_group m_threadGroup;
    };
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	CThreadBase threadBase;
    
    	//设置最大的线程个数。
    	threadBase.Start(5);
    	threadBase.Stop();
    
    	system("PAUSE");
    
    	return 0;
    }
    

    在这个例子里封装了一个类CThreadBase,这个类可以表示一个线程运行, 也可以多个线程运行,并且可以让线程运行类里的成员函数,这样更加方便添加代码和管理代码了。在这个例子里,要注意的就是bind器的使用,如下:

    m_threadGroup.create_thread(boost::bind(&CThreadBase::Run, this,i));

    首先获取成员函数的指针,然后再传送this指针过去,然后就可以调用类实例化的成员函数了。


  • 相关阅读:
    ubuntu16.04添加开机启动任务
    Elasticsearch-5.0.0移植到ubuntu16.04
    转:解决npm install慢的问题
    解决virtualbox装ghost xp装驱动时报portcls.sys蓝屏的问题
    git文件迁移到新架构
    ubuntu16.04文件形式安装mongodb
    linux启动流程
    启动WAMPSERVER出现计算机中丢失 MSVCR110.dll
    socket编程的网络协议
    PHP7的新特性
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3034447.html
Copyright © 2011-2022 走看看