天天看點

boost庫封裝Thread

曾經嘗試對pthread進行封裝,使用Thread虛基類,子類重寫run方法的方式。詳情見:

C++封裝POSIX 線程庫(三)線程的封裝

最近閱讀 以boost::function和boost:bind取代虛函數學習了使用boost::function和boost::bind對Thread庫進行封裝。

令Thread是一個具體類,其構造函數接收ThreadCallback對象。應用程式隻需提供一個能夠轉換為ThreadCallback的對象,即可建立Thread實體,然後調用start()即可。Java中的Thread可以這麼用,傳入一個Runnable對象。

下面實作了一個基于boost::function的簡單的Thread Class

//Thread.h

#ifndef __THREAD_H__
#define __THREAD_H__
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <unistd.h>
#include <vector>
#include <memory>

using namespace std;
using namespace boost;

class Thread{
public:
    typedef boost::function<void()> ThreadCallback;
    explicit Thread(const ThreadCallback&);
    void start();
    void join();
    private:
    void run()
    {
        cb_();
    }
    ThreadCallback cb_;
    static void * RunInThread(void *);

    pthread_t threadId_;
};
#endif 
           
//Thread.cpp

#include "Thread.h"

Thread::Thread(const ThreadCallback& cb ):cb_(cb),threadId_()
{
}


void Thread::start()
{
    pthread_create(&threadId_,NULL,RunInThread,this);
}


void * Thread::RunInThread(void * arg)
{
    Thread * pt= static_cast<Thread*>(arg);
    pt->run();
}

void Thread::join()
{
     pthread_join(threadId_, NULL);
}
           

下面是相關測試程式。

//main.cpp

#include "Thread.h"
void threadFunc1(int a,int b,int c,int d)
{
    cout<<a<<b<<c<<d<<endl;
    sleep();
}
void threadFunc2()
{
    cout<<"threadFunc2"<<endl;
    sleep();
}
class Foo
{
    private:
    int count_;
    public :
    Foo(int count):count_(count){}
    void threadFunc(int a)
    {
        while(count_--)
        {
            cout << "Foo func"<<a<<endl;
            sleep();
        }
    }
};
int main()
{
    int a=;
    int b=;
    int c=;
    int d=;

    typedef std::shared_ptr<Thread> ThreadPtr;
    Foo foo();
    {
    vector<ThreadPtr> threads();
#if 1
        threads[].reset(new Thread(boost::bind(threadFunc1,a,b,c,d)));
        threads[].reset(new Thread(boost::bind(threadFunc2)));
        threads[].reset(new Thread(boost::bind(&Foo::threadFunc,&foo,)));

        threads[]->start();
        threads[]->join();
        threads[]->start();
        threads[]->join();
        threads[]->start();
        threads[]->join();
#endif 
    }
    return ;
}
           

結果如圖:

boost庫封裝Thread

參考

1.《Linux多線程服務端程式設計 使用muduo C++網絡庫》

2.http://blog.csdn.net/jnu_simba/article/details/12944043

3.http://blog.csdn.net/solstice/article/details/3066268

4.http://blog.csdn.net/zhangxiao93/article/details/52040369?locationNum=7&fps=1

繼續閱讀