• C++多线程的用法(包含线程池小项目)


    一些小Tips: 

    • linux环境下,编译多线程程序时,需要加上后缀 -lpthread 引入线程库:
     g++ 7.thread_pool.cpp -lpthread
    • bash下查看一个可执行程序的运行时间:
    time ./a.out
    •   需要引入的库函数有:
    1. #include // 引入线程库
    2. #include // 加入锁机制需要引入库函数mutex
    3. #include // 引入信号量机制
    •  在C++程序中获得本进程的进程id:
    this_thread::get_id()
    • 在C++程序中如何定义信号量、锁:
    1. condition_variable m_cond // 信号量
    2. std::mutex m_mutex; // 互斥锁,在非std命名空间的情况下
    • 一个线程的栈所占用的空间有多大?——8M。查看命令:
    ulimit -a

    多线程概念:

    • 进程是资源分配的最基本单位;线程是进程中的概念,是调度的基本单位,共享进程空间资源。
    • 什么是临界资源?——多线程情况下,大家都能访问到的资源。
    • 所谓的多线程只不过就是指定的某一个执行函数为入口函数的另外一套执行流程。

    代码样例:

    1. #include
    2. #include
    3. using namespace std;
    4. #define BEGINS(x) namespace x{
    5. #define ENDS(x) }
    6. BEGINS(thread_usage) // 自定义命名空间
    7. void func() {
    8. cout << "hello wolrd" << endl;
    9. return ;
    10. }
    11. int main() {
    12. thread t1(func); // t1已经开始运行了
    13. t1.join(); // 等待t1线程结束
    14. return 0;
    15. }
    16. ENDS(thread_usage)
    17. int main() {
    18. thread_usage::main(); // 调用该命名空间下的main函数
    19. return 0;
    20. }
    • 那么如何给入口函数传参呢? 在C++中就很简单:
    1. void print(int a, int b) {
    2. cout << a << " " << b << endl;
    3. return ;
    4. }
    5. int main() {
    6. thread t2(print, 3, 4);
    7. t2.join();
    8. return 0;
    9. }

    多线程设计理念:

    • 多线程封装思维:在相应的功能函数内部,不要去访问全局变量,类似于一个原子操作的功能。本身就支持多线程并行。
    • 多线程程序设计:线程功能函数和入口函数要分开。(高内聚低耦合)
    • 能不用锁就不用锁,因为这个锁机制会给程序运行效率带来极大的影响。

    1. 多线程实现素数统计的功能

    1.1. 不加锁版:

    1. #include
    2. #include
    3. #include
    4. #include
    5. using namespace std;
    6. #define BEGINS(x) namespace x{
    7. #define ENDS(x) }
    8. BEGINS(is_prime)
    9. bool is_prime(int x) {
    10. for (int i = 2, I = sqrt(x); i <= I; i++) {
    11. if (x % i == 0) return false;
    12. }
    13. return true;
    14. }
    15. // 多线程——功能函数
    16. int prime_count(int l, int r) {
    17. // 从l到r范围内素数的数量
    18. int ans = 0;
    19. for (int i = l; i <= r; i++) {
    20. ans += is_prime(i);
    21. }
    22. return ans;
    23. }
    24. // 多线程——入口函数
    25. void worker(int l, int r, int &ret) {
    26. cout << this_thread::get_id() << "begin" << endl;
    27. ret = prime_count(l, r);
    28. cout << this_thread::get_id() << "dnoe" << endl;
    29. }
    30. int main() {
    31. #define batch 500000
    32. thread *t[10];
    33. int ret[10];
    34. for (int i = 0, j = 1; i < 10; i++, j += batch) {
    35. t[i] = new thread(worker, j, j + batch - 1, ref(ret[i]));
    36. }
    37. for (auto x : t) x->join();
    38. int ans = 0;
    39. for (auto x : ret) ans += x;
    40. for (auto x : t) delete x;
    41. cout << ans << endl;
    42. #undef batch
    43. return 0;
    44. }
    45. ENDS(is_prime)
    46. int main() {
    47. // thread_usage::main();
    48. is_prime::main();
    49. return 0;
    50. }
    • 运行时间:总时长0.512s,系统时间0.02s,用户时间1.92s

    1.2. 加锁版:

    1. #include
    2. #include
    3. #include
    4. #include
    5. using namespace std;
    6. #define BEGINS(x) namespace x{
    7. #define ENDS(x) }
    8. BEGINS(prime_count2)
    9. int ans = 0;
    10. std::mutex m_mutex;
    11. bool is_prime(int x) {
    12. for (int i = 2, I = sqrt(x); i <= I; i++) {
    13. if (x % i == 0) return false;
    14. }
    15. return true;
    16. }
    17. void prime_count(int l, int r) {
    18. cout << this_thread::get_id() << " begin\n";
    19. for (int i = l; i <= r; i++) {
    20. std::unique_lock lock(m_mutex); // 临界区
    21. ans += is_prime(i);
    22. lock.unlock();
    23. }
    24. cout << this_thread::get_id() << " done\n";
    25. return ;
    26. }
    27. int main() {
    28. #define batch 500000
    29. thread *t[10];
    30. for (int i = 0, j = 1; i < 10; i++, j += batch) {
    31. t[i] = new thread(prime_count, j, j + batch - 1);
    32. }
    33. for (auto x : t) x->join();
    34. for (auto x : t) delete x;
    35. cout << ans << endl;
    36. #undef batch
    37. return 0;
    38. }
    39. ENDS(prime_count2)
    40. int main() {
    41. prime_count2::main();
    42. return 0;
    43. }
    • 运行时间:总时长5.916s,系统时间7.44s,用户时间6.50s

    显然能够看出,加了锁要比不加锁耗时得多。所以加锁的行为要慎重。

    1.3. 引入原子操作版:

    • 为什么不用++而是用+=:因为+=是原子操作,而++不是,所以++操作在多线程情况下可能存在覆盖写的问题。
    • 为什么使用__sync_fetch_and_add函数:因为这个函数也是原子操作。
    1. #include
    2. #include
    3. #include
    4. #include
    5. using namespace std;
    6. #define BEGINS(x) namespace x{
    7. #define ENDS(x) }
    8. BEGINS(thread3)
    9. int ans = 0;
    10. bool is_prime(int x) {
    11. for (int i = 2, I = sqrt(x); i <= I; i++) {
    12. if (x % i == 0) return false;
    13. }
    14. return true;
    15. }
    16. void prime_count(int l, int r) {
    17. cout << this_thread::get_id() << "begin\n";
    18. for (int i = l; i <= r; i++) {
    19. int ret = is_prime(i);
    20. __sync_fetch_and_add(&ans, ret);
    21. }
    22. cout << this_thread::get_id() << "done\n";
    23. }
    24. int main() {
    25. #define batch 500000
    26. thread *t[10];
    27. for (int i = 0, j = 1; i < 10; i++, j += batch) {
    28. t[i] = new thread(prime_count, j, j + batch - 1);
    29. }
    30. for (auto x : t) x->join();
    31. for (auto x : t) delete x;
    32. cout << ans << endl;
    33. #undef batch
    34. return 0;
    35. }
    36. ENDS(thread3)
    37. int main() {
    38. thread3::main();
    39. return 0;
    40. }

    • - `2.06s user`:表示程序在用户态消耗的CPU时间为2.06秒。这是程序执行期间用于执行用户代码的时间。
    • - `0.02s system`:表示程序在内核态消耗的CPU时间为0.02秒。这是程序执行期间用于执行内核代码的时间。
    • - `385% cpu`:表示程序使用了385%的CPU资源。这个值超过100%是因为程序可能在多个CPU核心上并行执行。所以 总时间 < 用户态+内核态时间 是非常正常的。
    • - `0.538 total`:表示程序从开始执行到结束的总时间为0.538秒。这是包括了实际执行时间、等待时间和其他非CPU消耗的时间。

    2. 小项目:线程池的实现

    • 线程作为一种内存资源,在通常的多线程设计模式下,申请线程资源并不可控。而我们自然希望申请内存的动作是可控的。
    • 一个好的解决办法就是限制一个池子的大小来存放一些线程贯穿程序运行周期始终,也就是线程池在线程池内部,线程数量是可控的。把一个个计算任务打包,扔到一个任务队列中,线程池中的线程争相从任务队列中领取任务并执行。这样就实现了资源的有效利用和管控。
    • 什么是计算任务?——分为过程(函数方法)和数据(函数参数);
    • 如何进行打包——bind()方法。

    代码实现:

    1. /*************************************************************************
    2. > File Name: threadpool.cpp
    3. > Author: jby
    4. > Mail:
    5. > Created Time: Wed 13 Sep 2023 08:48:23 AM CST
    6. ************************************************************************/
    7. #include
    8. #include
    9. #include
    10. #include
    11. #include
    12. #include
    13. #include
    14. #include
    15. #include
    16. using namespace std;
    17. #define BEGINS(x) namespace x {
    18. #define ENDS(x) }
    19. BEGINS(thread_pool_test)
    20. class Task {
    21. public:
    22. template<typename FUNC_T, typename ...ARGS>
    23. Task(FUNC_T func, ARGS ...args) {
    24. this->func = bind(func, forward(args)...);
    25. }
    26. void run() {
    27. func();
    28. return ;
    29. }
    30. private:
    31. function<void()> func; // 任意函数
    32. };
    33. class ThreadPool {
    34. public:
    35. ThreadPool(int n = 1) : thread_size(n), threads(n), starting(false) {
    36. this->start();
    37. return ;
    38. }
    39. void worker() {
    40. auto id = this_thread::get_id(); // 获得本进程号
    41. running[id] = true;
    42. while (running[id]) {
    43. // 取任务
    44. Task *t = get_task();
    45. t->run();
    46. delete t;
    47. }
    48. return ;
    49. }
    50. void start() {
    51. if (starting == true) return ; // 如果已经开始了就不用启动了
    52. for (int i = 0; i < thread_size; i++) {
    53. threads[i] = new thread(&ThreadPool::worker, this);
    54. }
    55. starting = true;
    56. return ;
    57. }
    58. template<typename FUNC_T, typename ...ARGS>
    59. void add_task(FUNC_T func, ARGS ...args) {
    60. unique_lock lock(m_mutex);
    61. tasks.push(new Task(func, forward(args)...)); // 任务池相当于临界资源
    62. m_cond.notify_one(); // 生产者消费者模型
    63. return ;
    64. }
    65. void stop() {
    66. if (starting == false) return ; // 如果已经关了就不用再关了
    67. for (int i = 0; i < threads.size(); i++) { // 往队列末尾投递毒药任务
    68. this->add_task(&ThreadPool::stop_runnnig, this);
    69. }
    70. for (int i = 0; i < threads.size(); i++) {
    71. threads[i]->join();
    72. }
    73. for (int i = 0; i < threads.size(); i++) {
    74. delete threads[i]; // 释放那片进程剩余的空间
    75. threads[i] = nullptr; // 进程指针指向空
    76. }
    77. starting = false;
    78. return ;
    79. }
    80. ~ThreadPool() {
    81. this->stop();
    82. while (!tasks.empty()) { // 如果任务队列里还有任务没执行完,全部丢弃
    83. delete tasks.front();
    84. tasks.pop();
    85. }
    86. return ;
    87. }
    88. private:
    89. bool starting;
    90. int thread_size;
    91. Task *get_task() {
    92. unique_lock lock(m_mutex);
    93. while (tasks.empty()) m_cond.wait(lock); // 生产者消费者模型 //子进程的中wait函数对互斥量进行解锁,同时线程进入阻塞或者等待状态。
    94. Task *t = tasks.front();
    95. tasks.pop();
    96. return t;
    97. }
    98. std::mutex m_mutex;
    99. std::condition_variable m_cond;
    100. vector threads; // 线程池子
    101. unordered_map<decltype(this_thread::get_id()), bool> running; // 进程号到运行状态的哈希映射
    102. queue tasks; // 任务队列
    103. void stop_runnnig() { // 毒药任务
    104. auto id = this_thread::get_id();
    105. running[id] = false;
    106. return ;
    107. }
    108. };
    109. bool is_prime(int x) {
    110. for (int i = 2, I = sqrt(x); i <= I; i++) {
    111. if (x % i == 0) return false;
    112. }
    113. return true;
    114. }
    115. int prime_count(int l, int r) {
    116. int ans = 0;
    117. for (int i = l; i <= r; i++) {
    118. ans += is_prime(i);
    119. }
    120. return ans;
    121. }
    122. void worker(int l, int r, int &ret) {
    123. cout << this_thread::get_id() << "begin\n";
    124. ret = prime_count(l, r);
    125. cout << this_thread::get_id() << "done\n";
    126. return ;
    127. }
    128. int main() {
    129. #define batch 500000
    130. ThreadPool tp(5); // 五个任务的窗口队列
    131. int ret[10];
    132. for (int i = 0, j = 1; i < 10; i++, j += batch) {
    133. tp.add_task(worker, j, j + batch - 1, ref(ret[i]));
    134. }
    135. tp.stop();
    136. int ans = 0;
    137. for (auto x : ret) ans += x;
    138. cout << ans << endl;
    139. #undef batch
    140. return 0;
    141. }
    142. ENDS(thread_pool_test)
    143. int main() {
    144. thread_pool_test::main();
    145. return 0;
    146. }

  • 相关阅读:
    K8S用户管理体系介绍
    记一次密码控制功能
    IDEA安装与配置
    【Ubuntu搭建MQTT Broker及面板+发布消息、订阅主题】
    SpringCLoud——服务的拆分和远程调用
    设计模式行为型-状态模式
    【Linux】linux中你不得不爱的命令集(上)
    线性代数应用基础补充2
    在进行自动化测试,遇到验证码的问题,怎么办?
    XTU-OJ 1108-a+b
  • 原文地址:https://blog.csdn.net/weixin_55252589/article/details/132843450