• 【Linux】线程池


    目录

    1. 线程池

    1.1. 什么是线程池

    1.2. 创建线程池

    2.线程安全的单例模式

    2.1. 什么是单例模式

    2.2. 饿汉方式实现单例模式

    2.3. 懒汉方式实现单例模式

    2.4. 基于懒汉方式实现单例模式下的线程池


    1. 线程池

    1.1. 什么是线程池

    线程虽然比进程轻量了很多,但是每创建一个线程时,需要向操作系统申请空间创建,如果需要开辟大量的线程,申请和销毁的开销也是很大的。所以如果能够提前申请一块空间,专门用来创建线程,那么就能提高一些效率。

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

    线程池通过一个线程安全的阻塞任务队列加上一个或一个以上的线程实现,线程池中的线程可以从阻塞队列中获取任务进行任务处理,当线程都处于繁忙状态时可以将任务加入阻塞队列中,等到其它的线程空闲后进行处理。

    线程池的作用:可以避免大量线程频繁创建或销毁所带来的时间成本,也可以避免在峰值压力下,系统资源耗尽的风险;并且可以统一对线程池中的线程进行管理,调度监控。

    线程池的应用场景:

    1. 需要大量的线程来完成任务,且完成任务的时间比较短。 WEB服务器完成网页请求这样的任务,使用线程池技术是非常合适的。因为单个任务小,而任务数量巨大,可以想象一个热门网站的点击次数。

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

    3. 接受突发性的大量请求,但不至于使服务器因此产生大量线程的应用。突发性大量客户请求,在没有线程池情况下,将产生大量线程,虽然理论上大部分操作系统线程数目最大值不是问题,短时间内产生大量线程可能使内存到达极限,导致出现错误

    1.2. 创建线程池

    其实质原理还是生产者消费者模型,通过一个线程创建任务,将任务放进任务队列中,线程池中的线程竞争任务。

    具体实现代码:

    task.hpp: (老熟人了)

    1. #pragma once
    2. #include
    3. #include
    4. using namespace std;
    5. class Task
    6. {
    7. private:
    8. int _x;
    9. int _y;
    10. char _op;
    11. public:
    12. Task() {}
    13. Task(int x, int y, char op) : _x(x), _y(y), _op(op)
    14. {}
    15. int option()
    16. {
    17. int ans = 0;
    18. switch (_op)
    19. {
    20. case '+':
    21. ans = _x + _y;
    22. break;
    23. case '-':
    24. ans = _x - _y;
    25. break;
    26. case '*':
    27. ans = _x * _y;
    28. break;
    29. case '/':
    30. ans = _x / _y;
    31. break;
    32. case '%':
    33. ans = _x % _y;
    34. break;
    35. default:
    36. cout << "error" << endl;
    37. break;
    38. }
    39. cout << "当前任务正在被消费者线程:" << pthread_self() << "处理-->" << _x << _op << _y << "=" << ans << endl;
    40. return ans;
    41. }
    42. int operator()()
    43. {
    44. return option();
    45. }
    46. };

     

    threadpool.hpp:

    1. #pragma once
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. using namespace std;
    8. template<class T>
    9. class ThreadPool
    10. {
    11. private:
    12. int _capacity;
    13. queue _task_queue; // 临界资源
    14. pthread_mutex_t _mtx;
    15. pthread_cond_t _cond;
    16. public:
    17. void Lock()
    18. {
    19. pthread_mutex_lock(&_mtx);
    20. }
    21. void Unlock()
    22. {
    23. pthread_mutex_unlock(&_mtx);
    24. }
    25. void Wait()
    26. {
    27. pthread_cond_wait(&_cond, &_mtx);
    28. }
    29. void Wakeup()
    30. {
    31. pthread_cond_signal(&_cond);
    32. }
    33. bool IsEmpty()
    34. {
    35. return _task_queue.empty();
    36. }
    37. public:
    38. ThreadPool(int capacity = 5):_capacity(capacity)
    39. {
    40. pthread_mutex_init(&_mtx, nullptr);
    41. pthread_cond_init(&_cond, nullptr);
    42. }
    43. ~ThreadPool()
    44. {
    45. pthread_mutex_destroy(&_mtx);
    46. pthread_cond_destroy(&_cond);
    47. }
    48. // 在类中要让线程执行类内成员方法是不可行的
    49. // 由于类中非静态成员隐含this指针,这里会导致传参出错,所以需要将该函数设置为静态
    50. static void* Rountine(void* args)
    51. {
    52. pthread_detach(pthread_self());
    53. ThreadPool*tq = (ThreadPool*) args;
    54. while(true)
    55. {
    56. tq->Lock();
    57. while(tq->IsEmpty()) // 任务队列为空
    58. {
    59. tq->Wait(); // 挂起
    60. }
    61. T t;
    62. tq->PopTask(&t);
    63. tq->Unlock();
    64. t(); // 处理任务
    65. //sleep(1);
    66. }
    67. }
    68. void InitThreadPool()
    69. {
    70. pthread_t tid;
    71. for(int i = 0; i < _capacity; ++i)
    72. {
    73. pthread_create(&tid, nullptr, Rountine, (void*)this);
    74. // 由于该执行任务函数为静态函数,不能访问类内成员,所以传参数时,需要传入this指针才能访问到类内成员
    75. } // 不需要记住每个线程的id,创建成功后将每个线程分离,不用手动等待
    76. }
    77. void PushTask(const T& in)
    78. {
    79. Lock();
    80. _task_queue.push(in);
    81. Unlock();
    82. Wakeup();
    83. }
    84. void PopTask(T* out)
    85. {
    86. *out = _task_queue.front();
    87. _task_queue.pop();
    88. }
    89. };

    main.cc:

    1. #include"thread_pool.hpp"
    2. #include"task.hpp"
    3. #include
    4. #include
    5. int main()
    6. {
    7. ThreadPool* tp = new ThreadPool;
    8. tp->InitThreadPool();
    9. srand((long long)time(nullptr));
    10. while(true)
    11. {
    12. Task t(rand()%20+1, rand()%10+1,"+-*/%"[rand()%5]);
    13. tp->PushTask(t);
    14. sleep(1);
    15. }
    16. }

    2.线程安全的单例模式

    2.1. 什么是单例模式

    一个类,只应该实例化出一个对象,就称为单例。

    定义对象的本质,是将对象加载到内存,只让该对象在内存中加载一次,就是单例。

    对象被设计成单例的场景:

    1. 语义上只需要一个对象

    2. 该对象内部存在大量的空间,保存了大量的数据,如果允许该对象存在多份,或者允许发生拷贝,内存中会存在数据冗余。

    什么时候加载对象呢?有两种模式:饿汉、懒汉

    2.2. 饿汉方式实现单例模式

    形象的说就是:吃完饭后,立即就将碗洗了。

    对于创建对象层面来说:创建类时,就立即创建出对应的对象。

    1. template <class T>
    2. class Singleton
    3. {
    4. static T data; // 静态成员,该成员属于类,不属于对象,一旦创建了类,该成员就被创建了
    5. public:
    6. static T* GetInstance()
    7. {
    8. return &data;
    9. }
    10. };
    11. template <class T>
    12. T Singleton:: data = T();

    只要通过 Singleton 这个包装类来使用 T 对象, 则一个进程中只有一个 T 对象的实例。

    2.3. 懒汉方式实现单例模式

    形象的说就是:吃完饭后,先把碗放下,下一顿饭用到这个碗了再洗碗。

    对于创建对象层面来说:延时加载,先不创建对应的对象,等到需要用到的时候才创建。(写时拷贝就用到了这个思想)

    1. template <class T>
    2. class Singleton
    3. {
    4. static T* inst; // 先创建静态成员的指针,指针指向空
    5. public:
    6. static T* GetInstance()
    7. {
    8. if (inst == nullptr)
    9. {
    10. inst = new T(); // 一旦调用了该函数(即需要用到该对象的时候),才创建该对象
    11. }
    12. return inst;
    13. }
    14. };
    15. template <class T>
    16. T* Singleton:: inst = nullptr;

    存在一个严重的问题, 线程不安全。

    第一次调用 GetInstance 的时候, 如果两个线程同时调用, 可能会创建出两份 T 对象的实例。

    所以需在创建单例时进行加锁。

    2.4. 基于懒汉方式实现单例模式下的线程池

    其中的大概框架还是线程池,只是创建对象的方式改变了。

    不会在main函数中一开就创建对象,而是在获取到任务之后才创建。并且实现了线程安全。

    具体实现代码:task.hpp:老熟人就不放了,上面可以参考

    thread_pool.hpp:

    1. #pragma once
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. using namespace std;
    8. template <class T>
    9. class ThreadPool
    10. {
    11. private:
    12. int _capacity;
    13. queue _task_queue; // 临界资源
    14. pthread_mutex_t _mtx;
    15. pthread_cond_t _cond;
    16. static ThreadPool *ins;
    17. private:
    18. // 构造函数必须得实现,但是必须私有化(即不能实例化对象)
    19. ThreadPool(int capacity = 5) : _capacity(capacity)
    20. {
    21. pthread_mutex_init(&_mtx, nullptr);
    22. pthread_cond_init(&_cond, nullptr);
    23. }
    24. ThreadPool(const ThreadPool &tp) = delete;
    25. // 赋值语句
    26. ThreadPool &operator=(ThreadPool &tp) = delete;
    27. public:
    28. void Lock()
    29. {
    30. pthread_mutex_lock(&_mtx);
    31. }
    32. void Unlock()
    33. {
    34. pthread_mutex_unlock(&_mtx);
    35. }
    36. void Wait()
    37. {
    38. pthread_cond_wait(&_cond, &_mtx);
    39. }
    40. void Wakeup()
    41. {
    42. pthread_cond_signal(&_cond);
    43. }
    44. bool IsEmpty()
    45. {
    46. return _task_queue.empty();
    47. }
    48. public:
    49. static ThreadPool *GetInstance() // 设置为静态函数该函数属于类,否则在main函数中,如果未实例化对象将不能调用该函数
    50. {
    51. static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    52. if (ins == nullptr) // 双判定,只有未创建单例对象时才竞争锁,减少锁的争用,提高获取单例的效率
    53. {
    54. pthread_mutex_lock(*lock);
    55. if (ins == nullptr) // 当前单例对象没有被创建
    56. {
    57. ins = new ThreadPool;
    58. ins->InitThreadPool();
    59. }
    60. pthread_mutex_unlock(&lock);
    61. }
    62. return ins;
    63. }
    64. ~ThreadPool()
    65. {
    66. pthread_mutex_destroy(&_mtx);
    67. pthread_cond_destroy(&_cond);
    68. }
    69. // 在类中要让线程执行类内成员方法是不可行的
    70. // 由于类中非静态成员隐含this指针,这里会导致传参出错,所以需要将该函数设置为静态
    71. static void *Rountine(void *args)
    72. {
    73. pthread_detach(pthread_self());
    74. ThreadPool *tp = (ThreadPool *)args;
    75. while (true)
    76. {
    77. tp->Lock();
    78. while (tp->IsEmpty()) // 任务队列为空
    79. {
    80. tp->Wait(); // 挂起
    81. }
    82. T t;
    83. tp->PopTask(&t);
    84. tp->Unlock();
    85. t(); // 处理任务
    86. // sleep(1);
    87. }
    88. }
    89. void InitThreadPool()
    90. {
    91. pthread_t tid;
    92. for (int i = 0; i < _capacity; ++i)
    93. {
    94. pthread_create(&tid, nullptr, Rountine, (void *)this); // 由于该执行任务函数为静态函数,不能访问类内成员,所以传参数时,需要传入this指针才能访问到类内成员
    95. }
    96. }
    97. void PushTask(const T &in)
    98. {
    99. Lock();
    100. _task_queue.push(in);
    101. Unlock();
    102. Wakeup();
    103. }
    104. void PopTask(T *out)
    105. {
    106. *out = _task_queue.front();
    107. _task_queue.pop();
    108. }
    109. };
    110. // 初始化类内静态成员
    111. template <class T>
    112. ThreadPool *ThreadPool::ins = nullptr;

    main.cc:

    1. #include"thread_pool.hpp"
    2. #include"task.hpp"
    3. #include
    4. #include
    5. int main()
    6. {
    7. // ThreadPool* tp = new ThreadPool; 单例模式下不能手动创建对象
    8. srand((long long)time(nullptr));
    9. while(true)
    10. {
    11. Task t(rand()%20+1, rand()%10+1,"+-*/%"[rand()%5]);
    12. // 单例本身会在任何场景,任何环境下被调用
    13. // GetInstance 本身可能被多个线程重入,所以会存在线程安全问题
    14. // 所以需在 GetInstance 内部加锁
    15. ThreadPool::GetInstance()->PushTask(t); // 需要用到该对象的时候才创建
    16. sleep(1);
    17. }
    18. }
  • 相关阅读:
    保存PyTorch模型为ONNX
    Linux本地部署1Panel现代化运维管理面板并实现公网访问
    Chat GPT:智能对话的下一步
    【甄选靶场】Vulnhub百个项目渗透——项目二十八:zico2-1(目录遍历,sqlite数据库写入,脏牛提权)
    MySQL语法
    数据库注入提权总结(一)
    蓝牙AOA定位那点事系列090:第一次转载伙伴的文章客观理性成熟的观点:UWB定位和蓝牙AOA比较
    Go语言切片
    《OpenHarmony开源鸿蒙学习入门》–API9的Stage模型说明
    红队框架列表
  • 原文地址:https://blog.csdn.net/Edward_Asia/article/details/126354664