c++ 封装线程库 3

1. 继承与重写run方法

我们封装了Thread类,并设置成员函数run()为纯虚函数,因此我们使用类继承,并重写run方法:

class IncCount : public Thread//增加计数线程
{
    private:
        int id_;
    public:
        IncCount(int id):id_(id){}
        void run()
        {
            for(int i=0;i < 10;i ++)
            {
                {
                    MutexLockGuard lock(mutex);
                    count++;
                    if (count == 12)
                    {
                        cond.notify();//通知
                    }
                    //打印信息方便调试
                    std::cout<<"thread : "<<id_<<" count : "<< count << std::endl;
                }//临界区
                sleep(1.5);//注:sleep不是同步原语,这里只是为了方便调试
            }
        }
};
class WatchCount: public Thread//监视线程
{
    private:
        int id_;
    public:
        WatchCount(int id):id_(id){}
        void run()
        {
            MutexLockGuard lock(mutex);//加锁
            while(count < 12)//这里用while防止虚假唤醒
            {
                cond.wait();
            }
            assert(count>=12);
            count+=125;
            std::cout<<"thread : "<<id_<<" count : "<< count << std::endl;
        }
};

如果用多态的话,可以用vector来保存父类指针,并初始化指向子类引用,不过使用vector<Thread*>我们时常会有困惑,那就是vector作为栈上变量,其程序结束变量生命期结束,

而容器中的指针所指向的对象需要我们手动去delete,这样就会容易出错。

boost库中提供shared_ptr(c++11已经加入std),可以避免这种内存泄露的错误:vector生命期结束,shared_ptr释放,对象的引用计数变为0,也就自动释放资源了。

#include "Thread.h"
#include "MutexLock.h"
#include "Condition.h"
#include  <vector>
#include <memory>
using namespace std;
MutexLock mutex;//互斥锁
Condition cond(mutex);//条件变量
int count =0;

int main()
{
    {
        vector< shared_ptr<Thread> > t(3);

        t[0].reset(new WatchCount(1));
        t[1].reset(new IncCount(2));
        t[2].reset(new IncCount(3));
        for(int i=0;i<3;i++)
        {
            t[i]->start();
        }
        for(int i=0;i<3;i++)
        {
            t[i]->join();
        }

    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zhangkele/p/9373621.html