thread_pool.h 1.09 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#pragma once

#include <pthread.h>
#include "task_queue.h"

// 定义一个节点结构体,用于线程池中的每个线程
struct node {
    Task_Queue& task_queue; // 引用任务队列
    bool& shutdown;         // 引用关闭标志
    // 构造函数,初始化任务队列和关闭标志
    node(Task_Queue& task_queue, bool& shutdown) : task_queue(task_queue), shutdown(shutdown) {}
};

// 定义线程池类
class Pthpool {
public:
    // 构造函数,初始化线程池,参数为线程数量
    Pthpool(int thread_cnt);
    // 析构函数,清理线程池
    ~Pthpool();
    // 添加任务到任务队列,参数为任务函数和任务参数
    void add_task(void* f(void*), void* arg);

private:
    int thread_cnt;         // 线程数量
    Task_Queue task_queue;  // 任务队列
    pthread_t* thread_pool; // 线程池,存储线程ID
    bool shutdown;          // 关闭标志,用于控制线程池的关闭
    node para;              // 节点,用于线程运行时传递参数
    // 静态方法,线程运行的主函数
    static void* run_thread(void* arg);
};