Linux学习记录——이십칠 多线程(4)


1、线程池

池化技术是一种以空间换时间的技术,在用户申请线程之前,系统就预先创建了一些线程,用户发来申请请求时,系统就把这个请求封装成任务请求发给线程,线程也就被调用了。线程池本质上是一个生产者消费者模型,线程池是消费者,用户是生产者。

接下来写的是简单的线程池的设计。

服务器中,有任务队列,和预先创建好的线程,有很多的客户端,发送请求给服务器,服务器把所有请求放在任务队列中,然后发放给线程们。我们要实现的就是简单的服务器的操作。

1、V1:简易版本

创建main.cc,ThreadPool.hpp,makefile

makefile

ThreadPool:main.cc
    g++ -o $@ $^ -std=c++11 -lpthread
.PHONY:clean
clean:
    rm -f ThreadPool

main.cc

#include "ThreadPool.hpp"
using namespace std;

int main()
{
    unique_ptr<ThreadPool<int>> tp(new ThreadPool<int>());//智能指针
    tp->init();
    tp->start();
    while(true)
    {
        //充当生产者
        sleep(1);
    }
    return 0;
}

ThreadPool_V1.hpp

#pragma once

#include <iostream>
#include <memory>//智能指针的头文件
#include <string>
#include <vector>
#include <queue>
#include <unistd.h>
#include <pthread.h>

const static int N = 5;

template<class T>
class ThreadPool
{
public:
    ThreadPool(int num = N):_num(num), _threads(num)//也可以不初始化_threads,因为我们用的是库,直接push就行
    {
        pthread_mutex_init(&_lock, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    static void* threadRoutine(void* args)//加static?类内的线程函数,要记得加static,放在静态区,因为在类内会有this指针,导致函数参数类型不对
    {
        pthread_deatach(pthread_self());
        while(true)
        {
            sleep(1);
            std::cout << pthread_self() << "running..." << std::endl;
        }
    }

    void init()
    {
        
    }

    void start()
    {
        for(int i = 0; i < _num; i++)
        {
            pthread_create(&_threads[i], nullptr, threadRoutine, nullptr);
        }
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
    }
private:
    std::vector<pthread_t> _threads;
    int _num;
    std::queue<T> _tasks;//使用STL的自动扩容
    pthread_mutex_t _lock;
    pthread_cond_t _cond;//当没有任务,所有线程应当休息,挂起,所以用条件变量来控制
};

没有任务,所有线程就都等待。写一个推送任务的函数,这个函数内部的操作要用锁保护起来,推送完后就唤醒线程,然后线程执行自己的函数。threadRoutine这个函数,因为不能直接用类内的成员,所以我们传this指针,然后把参数args强制转换成ThreadPool类型,把它所要用的函数都写出来放在类中以供调用。

template<class T>
class ThreadPool
{
public:
    ThreadPool(int num = N):_num(num), _threads(num)//也可以不初始化_threads,因为我们用的是库,直接push就行
    {
        pthread_mutex_init(&_lock, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    void LockQueue() {pthread_mutex_lock(&_lock); }
    void UnlockQueue() {pthread_mutex_unlock(&_lock); }
    void ThreadWait() {pthread_cond_wait(&_cond, &_lock); 
    void ThreadWakeup() {pthread_cond_signal(&_cond); }
    bool isEmpty() {return _tasks.empty(); }
    
    T popTask()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }

    static void* threadRoutine(coid* args)//加static?类内的线程函数,要记得加static,放在静态区,因为在类内会有this指针,导致函数参数类型不对
    {
        pthread_deatach(pthread_self());
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args); 
        while(true)
        {
            //1、检测有没有任务,有就处理,无就等待,这里一定要加锁
            tp->LockQueue();
            //因为是静态函数,不能直接访问类内私有成员,所以create函数那里要传this指针就可以了
            if(tp->isEmpty())
            {
                tp->threadWait();
            }
            T t = tp->popTask()//从公共区域拿到私有区域
            tp->UnlockQueue();
            t.run();//处理任务
        }
    }

    void init()
    {
        ;
    }

    void start()
    {
        for(int i = 0; i < _num; i++)
        {
            pthread_create(&_threads[i], nullptr, threadRoutine, this);
        }
    }

    void pushTask(const T& t)
    {
        LockQueue();
        _task.push(t);
        ThreadWakeup();
        UnlockQueue();
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
    }
private:
    std::vector<pthread_t> _threads;
    int _num;
    std::queue<T> _tasks;//使用STL的自动扩容
    pthread_mutex_t _lock;
    pthread_cond_t _cond;//当没有任务,所有线程应当休息,挂起,所以用条件变量来控制
};

接下来是run函数。锁需要保护的是获取数据,而不是处理数据,所以run函数应当在解锁之后执行。

现在做一下测试,用之前的task.hpp文件。

    static void* threadRoutine(coid* args)//加static?类内的线程函数,要记得加static,放在静态区,因为在类内会有this指针,导致函数参数类型不对
    {
        pthread_deatach(pthread_self());
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args); 
        while(true)
        {
            //1、检测有没有任务,有就处理,无就等待,这里一定要加锁
            tp->LockQueue();
            //因为是静态函数,不能直接访问类内私有成员,所以create函数那里要传this指针就可以了
            if(tp->isEmpty())
            {
                tp->threadWait();
            }
            T t = tp->popTask()//从公共区域拿到私有区域
            tp->UnlockQueue();
            //测试
            t();
            std::cout << "thread handler done, result: " <<t.formatRes() << std::endl;
            //t.run();//处理任务
        }
    }
    
int main()
{
    unique_ptr<ThreadPool<int>> tp(new ThreadPool<int>());//智能指针
    tp->init();
    tp->start();
    while(true)
    {
        int x, y;
        char op;
        cout << "please enter x: " << endl; 
        cin >> x;
        cout << "please enter y: " << endl; 
        cin >> y;
        cout << "please enter op(+-*/%): " << endl; 
        cin >> op;
        Task t(x, y, op);
        tp->pushTask(t);
        //充当生产者,从网络中读取数据,构建成为任务,推送给线程池
        sleep(1);
        tp->pushTask();
    }
    return 0;
}

2、V2:用线程类来封装

之前写过一个有线程类的文件Thread.hpp

#pragma once

#include <iostream>
#include <pthread.h>
#include <string>
#include <cstdlib>
using namespace std;

typedef void (*func_t)();

class Thread
{
public:
    typdef enum
    {
        New = 0,
        RUNNING,
        EIXTED
    }ThreadStatus;
    typedef void (*func_t)(void*);
public:
    Thread(int num, func_t func, void* args):_tid(0), _status(NEW), _func(func), _args(args)//num是线程编号
    {
        char name[128];
        snprintf(name, sizeof(name), "thread-%d", num);
        _name = name;
    }

    int status() {return _status;}
    string threadname() {return _name;}
    pthread_t threadid()
    {
        if(_status == RUNNING) return _tid;
        else
        {
            return 0;
        }
    }

    //runHelper是成员函数,类的成员函数具有默认参数this,也就是括号有一个Thread* this,pthread_create的参数应当是void*类型,就不符合,所以加上static,放在静态区,就没有this,但是又有新问题了
    //static成员函数无法直接访问类内属性和其他成员函数,所以create那里要传this指针,this就是当前线程对象,传进来才能访问类内的东西
    static void* runHelper(void* args)//args就是执行方法的参数
    {
        Thread* ts = (Thread*)args;//就拿到了当前对象
        //函数里可以直接调用func这个传过来的方法,参数就是_args
        (*ts)();//调用了func函数
        return nullptr;
    }

    void operator()()//仿函数
    {
        if(_func != nullptr) _func(_args);
    }
    
    void run()//run函数这里传方法
    {
        int n = pthread_create(&_tid, nullptr, runHelper, this);//为什么传this?
        if(n != 0) exit(1);
        _status = RUNNING;
    }
 
    void join()
    {
        int n = pthread_join(_tid, nullptr);
        if(n != 0)
        {
            cerr << "main thread join thread" << _name << "error" << endl;
            return ;
        } 
        _status = EXITED;
    }
    
    ~Thread()
    {}
private:
    pthread_t _tid;
    string _name;
    func_t func;//线程未来要执行的函数方法
    void* _args;//也可以不写这个,那么typedef的函数指针就没有参数。当然,参数也可用模板来写
    ThreadStatus _status;
}

用这个文件代替库中的pthread.h头文件。

//这几个函数需要做改动,以及threadRoutine函数类型改成static void即可。
    void init()
    {
        //插入若干个线程
        for(int i = 0; i < _num; i++)
        {
            _threads.push_back(Thread(i, threadRoutine, this));
            //pthread_create(&_threads[i], nullptr, threadRoutine, this);
        }
    }

    void start()
    {
        for(auto& t: _threads)
        {
            t.run();
        }
    }

    void check()
    {
        for(auto& t: _threads)
        {
            std::cout << t.threadname() << "running..." << std::endl;
        }
    }

    ~ThreadPool()
    {
        for(auto& t: _threads)
        {
            t.join();
        }
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
    }
private:
    std::vector<Thread> _threads;//pthread_t是用的库中的
    int _num;
    std::queue<T> _tasks;//使用STL的自动扩容
    pthread_mutex_t _lock;
    pthread_cond_t _cond;//当没有任务,所有线程应当休息,挂起,所以用条件变量来控制

3、V3:用线程类 + 锁来封装

我们之前也写过一个互斥锁的简单封装,所以这里就用这个锁的类来改一下文件

LockGuard.hpp

#pragma once

#include <iostream>
#include <pthread.h>

class Mutex//自己不维护锁,由外部传入
{
public:
    Mutex(pthread_mutex_t *mutex):_pmutex(mutex)
    {} 
    
    void lock()
    {
        pthread_mutex_lock(_pmutex);
    }
    
    void unlock()
    {
        pthread_mutex_unlock(_pmutex);
    }
 
    ~Mutex()
    {}
private:
    pthread_mutex_t *_pmutex;
}

class LockGuard//自己不维护锁,由外部传入
{
public:
    LockGuard(pthread_mutex_t *mutex):_mutex(mutex)
    {
        _mutex.lock();
    }
    
    ~LockGuard()
    {
        _mutex.unlock();
    }
private:
     Mutex _mutex;
}

一切加锁和解锁都可以用类来自动完成,而在threadRoutine函数中就得调用类中的函数来写。

ThreadPool_V3.hpp

#pragma once

#include <iostream>
#include <memory>//智能指针的头文件
#include <string>
#include <vector>
#include <queue>
#include <unistd.h>
#include "Thread.hpp"
#include "task.hpp"
#include "LockGuard.hpp"

const static int N = 5;

template<class T>
class ThreadPool
{
public:
    ThreadPool(int num = N):_num(num), _threads(num)//也可以不初始化_threads,因为我们用的是库,直接push就行
    {
        pthread_mutex_init(&_lock, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    void pthread_mutex_t* getlock() {return &_lock; }
    void ThreadWait() {pthread_cond_wait(&_cond, &_lock); 
    void ThreadWakeup() {pthread_cond_signal(&_cond); }
    bool isEmpty() {return _tasks.empty(); }

    T popTask()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }

    static void threadRoutine(coid* args)//加static?类内的线程函数,要记得加static,放在静态区,因为在类内会有this指针,导致函数参数类型不对
    {
        pthread_deatach(pthread_self());
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args); 
        while(true)
        {
            T t;
            {//括号里就是临界区
                //1、检测有没有任务,有就处理,无就等待,这里一定要加锁
                LockGuard lockguard(tp->getlock());
                //因为是静态函数,不能直接访问类内私有成员,所以create函数那里要传this指针就可以了
                if(tp->isEmpty())
                {
                    tp->threadWait();
                }
                t = tp->popTask()//从公共区域拿到私有区域
            }
            //测试
            t();
            std::cout << "thread handler done, result: " <<t.formatRes() << std::endl;
            //t.run();//处理任务
        }
    }

    void init()
    {
        //插入若干个线程
        for(int i = 0; i < _num; i++)
        {
            _threads.push_back(Thread(i, threadRoutine, this));
        }
    }

    void start()
    {
        for(auto& t: _threads)
        {
            t.run();
        }
    }

    void check()
    {
        for(auto& t: _threads)
        {
            std::cout << t.threadname() << "running..." << std::endl;
        }
    }

    void pushTask(const T& t)
    {
        LockGuard lockguard(&_lock);//V2是调用系统接口,V3就是调用我们自己写的类,初始化,函数结束时自动析构,也就是释放锁
        _task.push(t);
        ThreadWait();
    }

    ~ThreadPool()
    {
        for(auto& t: _threads)
        {
            t.join();
        }
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
    }
private:
    std::vector<Thread> _threads;//pthread_t是用库中的
    int _num;
    std::queue<T> _tasks;//使用STL的自动扩容
    pthread_mutex_t _lock;
    pthread_cond_t _cond;//当没有任务,所有线程应当休息,挂起,所以用条件变量来控制
};

2、线程安全的单例模式——V4

单例模式是类只实例化一个对象的模式。有饿汉和懒汉实现方式。饿汉是程序加载进内存时就实例化对象,懒汉是用的时候才实例化。

现在我们把线程池设计成单例的,让整个线程池只有一个,由我们控制,用户只能获取。我们要定义一个静态的线程池对象,对它的初始化要放在类外。构造函数需要私有化,不去掉,去掉C++默认生成的拷贝构造,=重载函数,析构函数还是public。然后就是禁止别人创建对象。

private:
    ThreadPool(int num = N):_num(num), _threads(num)//也可以不初始化_threads,因为我们用的是库,直接push就行
    {
        pthread_mutex_init(&_lock, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ThreadPool(const ThreadPool<T>& tp) = delete;//去掉默认生成的函数
    void operator = (const ThreadPool<T>& tp) = delete;//去掉默认生成的函数
public:
    static ThreadPool<T>* getinstance()//这个要设置成静态的,因为如果cc文件中要调用这个静态对象的函数的话,函数也应当是静态的才行
    {
        if(nullptr == instance)
        {
            instance = new ThreadPool<T>();
        }
        return instance;
    }
    //...
private:
    std::vector<Thread> _threads;//pthread_t是用库中的
    int _num;
    std::queue<T> _tasks;//使用STL的自动扩容
    pthread_mutex_t _lock;
    pthread_cond_t _cond;//当没有任务,所有线程应当休息,挂起,所以用条件变量来控制
    static ThreadPool<T>* instance;//对象
};

template<class T>
ThreadPool<T>* ThreadPool<T>::instance = nullptr;//类外初始化

main.cc中先去掉和tp有关的代码

#include "ThreadPool.hpp"
#include "task.hpp"
using namespace std;

int main()
{
    /*unique_ptr<ThreadPool<int>> tp(new ThreadPool<int>());//智能指针
    tp->init();
    tp->start();*/
    while(true)
    {
        int x, y;
        char op;
        cout << "please enter x: " << endl; 
        cin >> x;
        cout << "please enter y: " << endl; 
        cin >> y;
        cout << "please enter op(+-*/%): " << endl; 
        cin >> op;
        Task t(x, y, op);
        ThreadPool<Task>::getinstance()->pushTask(t);
        //tp->pushTask(t);
        //充当生产者,从网络中读取数据,构建成为任务,推送给线程池
        sleep(1);
        tp->pushTask();
    }
    return 0;
}

在main.cc的while之前写上ThreadPool< Task >::getinstance(),创建一个对象。运行起来后,我们并不能得到想要的结果,输入xyop后没反应,这是因为虽然上面代码中new了一个,但是没有初始化。

    static ThreadPool<T>* getinstance()//这个要设置成静态的,因为如果cc文件中要调用这个静态对象的函数的话,函数也应当是静态的才行
    {
        if(nullptr == instance)
        {
            instance = new ThreadPool<T>();
            instance->init();
            instance->start();
        }
        return instance;
    }

现在我们的代码是没有问题,但是单例对象也可以在多线程中使用,那么此时上面的代码就不对了。getinstance中,如果一个线程new了一个,紧接着被切走了,然后后面几个线程也都new一个对象,那么系统中就有很多个对象了,也就不是单例了,所以我们需要加锁,锁也得是静态的。

    static ThreadPool<T>* getinstance()//这个要设置成静态的,因为如果cc文件中要调用这个静态对象的函数的话,函数也应当是静态的才行
    {
        LokcGuard lockguard(&instance_lock);//用锁类
        if(nullptr == instance)
        {
            instance = new ThreadPool<T>();
            instance->init();
            instance->start();
        }
        return instance;
    }
    //...
    static ThreadPool<T>* instance;//对象
    static pthread_mutex_t instance_lock;//静态锁
};

template<class T>
ThreadPool<T>* ThreadPool<T>::instance = nullptr;//类外初始化

template<class T>
pthread_mutex_t ThreadPool<T>::instance_lock = PTHREAD_MUTEX_INITIALIZER;

单例对象初始化那里,其实初始化只会发生一次,但是每个线程都得去加锁,然后判断一下,所以锁放在那里有点不合适。

    static ThreadPool<T>* getinstance()//这个要设置成静态的,因为如果cc文件中要调用这个静态对象的函数的话,函数也应当是静态的才行
    {
        if(nullptr == instance)//提高效率
        {
            LokcGuard lockguard(&instance_lock);//用锁类
            if(nullptr == instance)
            {
                instance = new ThreadPool<T>();
                instance->init();
                instance->start();
            }
        }
        return instance;
    }

只有第一次会进入if中,然后加锁,然后初始化,之后的线程只会判断一次然后直接返回。

到此结束,V4版本是最终版本,之后还会使用这个文件。

3、智能指针、线程安全

STL中的大部分容器都不是安全的,因为它们设计的初衷就不是考虑线程安全的。

智能指针中,unique_ptr也不涉及线程安全问题,shared_ptr用引用计数来解决线程安全,也有别的解决办法。

4、常见的各种锁

在这里插入图片描述

当申请锁失败时,自旋锁不会让申请的线程挂起,系统会让它持续申请,轮询式查看能否申请成功。互斥锁申请失败就会挂起等待,自旋锁则会频繁申请,这个动作也称为自旋。自旋还是挂起等待,要看访问临界区的时间,如果很长就挂起等待,时间短就自旋,自旋很消耗CPU的时间。

看一下如何使用自旋锁。要引用头文件pthread.h,pthread_spinlock_lock,pthread_spinlock_init,pthread_spinlock_destory,pthread_spinlock_trylock,pthread_spinlock_unlock。lock函数会自旋申请锁,trylock如果申请失败也就返回了。自旋锁和之前的锁的写法一样。

5、读者写者问题

读写端,写写之间是互斥的,读读之间是没有关系的,读写是互斥和同步的。在之前的生产消费模型中,消费者之间是互斥的,而读者之间没有关系,是因为读者不拿走数据。读写者有读写锁。pthread_rwlock_init等函数,用法和互斥锁一样。读者加锁是pthread_rdlock,写者加锁是pthread_wrlock。

看一个伪代码

int reader_cnt = 0;//读者数量
pthread_mutex_t lock;//锁
sem_t w(1);//写者要加载的信号量

//读者
pthread_mutex_lock(&lock)
if(reader_cnt == 0) P(w);//读者申请信号量,写者就拿不到了
reader_cnt++;
pthread_mutex_unlock(&lock)
//读者退出时
pthread_mutex_lock(&lock)
reader_cnt--;
if(reader_cnt == 0) V(w)//写者可以进来了
pthread_mutex_unlock(&lock)

//写者
P(w);//申请信号量
if(reader_cnt > 0)//说明还有读者,那就释放锁,做V操作,然后就不做写操作了 
{
    V(w);
    挂起等待;
}
 //到了这里,说明没有读者了,就可以写入
 V(w)

如果读者很多,一直在P,写者长时间无法拿到信号量,就会导致写者饥饿问题,也就是一个线程长时间申请不到锁。针对这个问题,有两个办法,读者优先和写者优先策略,上述代码就是读者优先。写者优先是写者来访问时,让当前读者读完,后面的读者不让读。大部分都使用读者优先,修改、写入的频率都比较低。原生线程库默认采用读者优先策略。即使改成写者优先,体现地也不够明显。

多线程部分结束,接下来就是网络。

本篇gitee

结束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值