• 线程池|单例模式|STL、智能指针线程安全|读者写者问题


    线程池

    线程池的逻辑思想:

    每当我们处理一个任务就要创建一个线程,创建线程的开销是很大的。因此我们可以预先创建一批线程,任务队列里没有任务的时候,每个线程都休眠,当队里中有任务的时候,就可以唤醒线程进行处理。唤醒线程的成本比创建整个线程的成本小,这就是线程池的逻辑思想。

    线程池的概念:

     线程池: 一种线程使用模式。线程过多会带来调度开销,进而影响缓存局部性和整体性能。而线程池维护着多个线程,等待着监督管理者分配可并发执行的任务。这避免了在处理短时间任务时创建与销毁线程的代价。线程池不仅能够保证内核的充分利用,还能防止过分调度。可用线程数量应该取决于可用的并发处理器、处理器内核、内存、网络sockets等的数量。

    线程池常见的应用场景:

    需要大量的线程来完成任务,且完成任务的时间比较短。

    对性能要求苛刻的应用,比如要求服务器迅速响应客户请求。

    接受突发性的大量请求,但不至于使服务器因此产生大量线程的应用。

    代码实现

    首先我们先熟悉一下整体的框架:

    Thread.hpp

    1. #pragma once
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. namespace ThreadNs
    8. {
    9. typedef std::function<void*(void*)> func_t;
    10. const int num =1024;
    11. class Thread
    12. {
    13. private:
    14. static void* start_routine(void*args)
    15. {
    16. Thread* _this = static_cast(args);
    17. return _this->callback();
    18. }
    19. public:
    20. Thread()
    21. {
    22. char namebuffer[num];
    23. snprintf(namebuffer,sizeof namebuffer,"thread-%d",threadnum++);
    24. name_ = namebuffer;
    25. }
    26. void start(func_t func,void*args = nullptr)
    27. {
    28. func_ = func;
    29. args_ = args;
    30. int n = pthread_create(&tid_,nullptr,start_routine,this);
    31. assert(n==0);
    32. (void)n;
    33. }
    34. void join()
    35. {
    36. int n = pthread_join(tid_,nullptr);
    37. assert(n==0);
    38. (void)n;
    39. }
    40. std::string threadname()
    41. {
    42. return name_;
    43. }
    44. ~Thread()
    45. {}
    46. void* callback()
    47. {
    48. return func_(args_);
    49. }
    50. private:
    51. std::string name_;
    52. func_t func_;
    53. void *args_;
    54. pthread_t tid_;
    55. static int threadnum;
    56. };
    57. int Thread::threadnum = 1;
    58. }

     LockGuard.hpp

    1. #include
    2. #include
    3. class Mutex
    4. {
    5. public:
    6. Mutex(pthread_mutex_t*lock_p=nullptr)
    7. :lock_p_(lock_p)
    8. {}
    9. void lock()
    10. {
    11. if(lock_p_) pthread_mutex_lock(lock_p_);
    12. }
    13. void unlock()
    14. {
    15. if(lock_p_) pthread_mutex_unlock(lock_p_);
    16. }
    17. ~Mutex()
    18. {}
    19. private:
    20. pthread_mutex_t * lock_p_;
    21. };
    22. class LockGuard
    23. {
    24. public:
    25. LockGuard(pthread_mutex_t*mutex)
    26. :mutex_(mutex)
    27. {
    28. mutex_.lock();
    29. }
    30. ~LockGuard()
    31. {
    32. mutex_.unlock();
    33. }
    34. private:
    35. Mutex mutex_;
    36. };

    ThreadPool.hpp

    1. #pragma once
    2. #include "Thread.hpp"
    3. #include "LockGuard.hpp"
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. using namespace ThreadNs;
    10. const int gnum = 3;
    11. template <class T>
    12. class ThreadPool;
    13. template <class T>
    14. class ThreadData
    15. {
    16. public:
    17. ThreadPool *threadpool;
    18. std::string name;
    19. public:
    20. ThreadData(ThreadPool *tp, const std::string &n) : threadpool(tp), name(n)
    21. { }
    22. };
    23. template <class T>
    24. class ThreadPool
    25. {
    26. private:
    27. static void *handlerTask(void *args)
    28. {
    29. ThreadData *td = (ThreadData *)args;
    30. ThreadPool *threadpool = static_cast *>(args);
    31. while (true)
    32. {
    33. T t;
    34. {
    35. LockGuard lockguard(td->threadpool->mutex());
    36. while(td->threadpool->isQueueEmpty())
    37. {
    38. td->threadpool->threadWait();
    39. }
    40. t = td->threadpool->pop();
    41. }
    42. std::cout << td->name << " 获取了一个任务" << t.toTaskString() << "并处理完成,结果是: " << t() << std::endl;
    43. }
    44. delete td;
    45. return nullptr;
    46. }
    47. public:
    48. void lockQueue() { pthread_mutex_lock(&_mutex); }
    49. void unlockQueue() { pthread_mutex_unlock(&_mutex); }
    50. bool isQueueEmpty() { return _task_queue.empty(); }
    51. void threadWait() { pthread_cond_wait(&_cond, &_mutex); }
    52. T pop()
    53. {
    54. T t = _task_queue.front();
    55. _task_queue.pop();
    56. return t;
    57. }
    58. void Push(const T &in)
    59. {
    60. LockGuard lockguard(&_mutex);
    61. _task_queue.push(in);
    62. pthread_cond_signal(&_cond);
    63. }
    64. pthread_mutex_t *mutex()
    65. {
    66. return &_mutex;
    67. }
    68. public:
    69. ThreadPool(const int &num = gnum) : _num(num)
    70. {
    71. pthread_mutex_init(&_mutex, nullptr);
    72. pthread_cond_init(&_cond, nullptr);
    73. for (int i = 0; i < _num; i++)
    74. {
    75. _threads.push_back(new Thread());
    76. }
    77. }
    78. void run()
    79. {
    80. for (const auto &t : _threads)
    81. {
    82. ThreadData *td = new ThreadData(this, t->threadname());
    83. t->start(handlerTask, td);
    84. std::cout << t->threadname() << "start..." << std::endl;
    85. }
    86. }
    87. ~ThreadPool()
    88. {
    89. pthread_mutex_destroy(&_mutex);
    90. pthread_cond_destroy(&_cond);
    91. for (const auto &t : _threads)
    92. delete t;
    93. }
    94. private:
    95. int _num;
    96. std::vector _threads;
    97. std::queue _task_queue;
    98. pthread_mutex_t _mutex;
    99. pthread_cond_t _cond;
    100. };

    我们将线程池进行了模板化,因此线程池当中存储的任务类型可以是任意的;现在我们想像之前处理各种数据的计算,那么先引入任务组件Task.hpp:

    1. #pragma once
    2. #include
    3. #include
    4. class Task
    5. {
    6. using func_t = std::function<int(int,int ,char)>;
    7. public:
    8. Task(){}
    9. Task(int x,int y,char op,func_t func)
    10. :_x(x),_y(y),_op(op),_callback(func)
    11. {}
    12. std::string operator()()
    13. {
    14. int result = _callback(_x,_y,_op);
    15. char buffer[1024];
    16. snprintf(buffer,sizeof buffer,"%d %c %d = %d",_x,_op,_y,result);
    17. return buffer;
    18. }
    19. std::string toTaskString()
    20. {
    21. char buffer[1024];
    22. snprintf(buffer,sizeof buffer,"%d %c %d = ?",_x,_op,_y);
    23. return buffer;
    24. }
    25. private:
    26. int _x;
    27. int _y;
    28. char _op;
    29. func_t _callback;
    30. };
    31. const std::string oper = "+-*/%";
    32. int mymath(int x,int y,char op)
    33. {
    34. int result = 0;
    35. switch(op)
    36. {
    37. case '+':
    38. result = x+y;
    39. break;
    40. case '-':
    41. result = x-y;
    42. break;
    43. case '*':
    44. result = x*y;
    45. break;
    46. case '/':
    47. if(y==0)
    48. {
    49. std::cerr<<"div zero error!"<
    50. result = -1;
    51. }
    52. else
    53. {
    54. result = x/y;
    55. }
    56. break;
    57. case '%':
    58. if(y==0)
    59. {
    60. std::cerr<<"mod zero error!"<
    61. result = -1;
    62. }
    63. else
    64. {
    65. result = x%y;
    66. }
    67. break;
    68. default:
    69. break;
    70. }
    71. return result;
    72. }

    main.cc

    1. #include "ThreadPool.hpp"
    2. #include "Thread.hpp"
    3. #include "Task.hpp"
    4. #include
    5. #include
    6. int main()
    7. {
    8. ThreadPool* tp = new ThreadPool();
    9. tp->run();
    10. srand(time(0));
    11. int x,y;
    12. char op;
    13. while(true)
    14. {
    15. x = rand()%10+1;
    16. y = rand()%20+1;
    17. op =oper[rand()%oper.size()];
    18. Task t(x,y,op,mymath);
    19. tp->Push(t);
    20. sleep(1);
    21. }
    22. return 0;
    23. }

    单例模式

    单例模式是一种创建型设计模式,它保证一个类只有一个实例存在,并且提供一个全局访问点来访问该实例。单例模式有饿汉模式和懒汉模式。

    洗完的例子:

    吃完饭 , 立刻洗碗 , 这种就是 饿汉方式 . 因为下一顿吃的时候可以立刻拿着碗就能吃饭 .
    吃完饭 , 先把碗放下 , 然后下一顿饭用到这个碗了再洗碗 , 就是 懒汉方式 .

    饿汉实现方式和懒汉实现方式

    饿汉方式实现单例模式

    1. template <typename T>
    2. class Singleton {
    3. static T data;
    4. public:
    5. static T* GetInstance() {
    6. return &data;
    7. }
    8. };

    懒汉方式实现单例模式

    1. template <typename T>
    2. class Singleton {
    3. static T* inst;
    4. public:
    5. static T* GetInstance() {
    6. if (inst == NULL) {
    7. inst = new T();
    8. }
    9. return inst;
    10. }
    11. };

    这样的懒汉设计可能会导致线程不安全,第一次调用 GetInstance 的时候, 如果两个线程同时调用, 可能会创建出两份 T 对象的实例。因此以下才是安全版的懒汉单例模式:

    // 懒汉模式 , 线程安全
    template
    class Singleton {
             volatile static T* inst; // 需要设置 volatile 关键字 , 否则可能被编译器优化 .
             static std::mutex lock;
    public:
             static T* GetInstance()
        {
                      if (inst == NULL) { // 双重判定空指针 , 降低锁冲突的概率 , 提高性能 .
                             lock.lock(); // 使用互斥锁 , 保证多线程情况下也只调用一次 new.
                      if (inst == NULL) {
                             inst = new T();
                       }
                lock.unlock();
         }
                    return inst;
        }
    };

     线程池的单例模式

    我们要做的第一步就是把构造函数私有,再把拷贝构造和赋值运算符重载delete:

     接下来就要在成员变量中定义一个静态指针,方便获取单例对象:

    在设置获取单例对象的函数的时候,注意要设置成静态成员函数,因为在获取对象前根本没有对象,无法调用非静态成员函数(无this指针):

    主函数的调用:

    不过也许会出现多个线程同时申请资源的场景,所以还需要一把锁来保护这块资源,而这把锁也得设置成静态,因为GetSingle()函数是静态的:

     STL,智能指针和线程安全

    STL 的设计初衷是将性能挖掘到极致 , 而一旦涉及到加锁保证线程安全 , 会对性能造成巨大的影响 . 而且对于不同的容器, 加锁方式的不同 , 性能可能也不同 ( 例如 hash 表的锁表和锁桶 ).
    因此 STL 默认不是线程安全 . 如果需要在多线程环境下使用 , 往往需要调用者自行保证线程安全 .

    对于 unique_ptr, 由于只是在当前代码块范围内生效, 因此不涉及线程安全问题.对于 shared_ptr, 多个对象需要共用一个引用计数变量, 所以会存在线程安全问题. 但是标准库实现的时候考虑到了这个问题, 基于原子操作(CAS)的方式保证 shared_ptr 能够高效, 原子的操作引用计数.

     其他常见的各种锁

    悲观锁:在每次取数据时,总是担心数据会被其他线程修改,所以会在取数据前先加锁(读锁,写锁,行锁等),当其他线程想要访问数据时,被阻塞挂起。

    乐观锁:每次取数据时候,总是乐观的认为数据不会被其他线程修改,因此不上锁。但是在更新数据前,会判断其他数据在更新前有没有对数据进行修改。主要采用两种方式:版本号机制和CAS操作。

    CAS操作:当需要更新数据时,判断当前内存值和之前取得的值是否相等。如果相等则用新值更新。若不等则失败,失败则重试,一般是一个自旋的过程,即不断重试

    自旋锁:使用自旋锁时,当多线程发生竞争锁的情况时,加锁失败的线程会忙等待(这里的忙等待可以用 while 循环等待实现),直到它拿到锁。而互斥锁加锁失败后,线程会让出 CPU 资源给其他线程使用,然后该线程会被阻塞挂起。如果成功申请临界资源的线程,临界区代码执行时间过长,自旋的线程会长时间占用 CPU 资源,所以自旋的时间和临界区代码执行的时间是成正比的关系。如果临界区代码执行的时间很短,就不应该使用互斥锁,而应该选用自旋锁。因为互斥锁加锁失败,是需要发生上下文切换的,如果临界区执行的时间比较短,那可能上下文切换的时间会比临界区代码执行的时间还要长。

     读者和写者问题:

     读者写者问题和生产者消费者模型的本质区别就是消费者会取走数据,而读者不会取走数据

    读写锁接口

    //初始化读写锁
    pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);


    //销毁读写锁
    pthread_rwlock_destroy(pthread_rwlock_t *rwlock);


    //读加锁
    pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);


    //写加锁
    pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);


    //解锁
    pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
     

     

  • 相关阅读:
    计算机网络 | 05.[HTTP] SSL/TLS握手过程
    如何启动Kotlin协程
    iPhone关闭隐私后,仍在收集数据
    nodeKey is required in setCurrentKey已解决
    MySQL数据库不会安装?看过来,保姆级安装详细教程来啦(图文结合,含安装包,包教包会)以及开启与关闭MySQL服务
    leetcode 第 361 场周赛
    Spring的Bean生命周期+bean注入+项目启动时正确姿势初始化数据的五种方式
    Kubernetes Namespace
    YOLO目标检测——汽车头部尾部检测数据集【含对应voc、coco和yolo三种格式标签】
    Vue 搜索历史管理-本地持久化管理
  • 原文地址:https://blog.csdn.net/m0_69005269/article/details/132759931