LINUX 入门 4

LINUX 入门 4

day6 7 20240429 20240504 耗时:240min

课程链接地址

第4章 LINUX环境编程——实现线程池

C基础

  1. 第3节

    1. #define里面的行不能乱空行,要换行就打\

    2. typedef 是 C 和 C++ 中的一个关键字,用于为已有的数据类型定义一个新的名字。通过 typedef 可以为数据类型起一个更直观或者更易于理解的名字,也可以用来简化复杂的数据类型声明。例如:

      unsigned long long int ULLONG; // 为 unsigned long long int 定义了一个新名字 ULLONG
      
    3. static void *nThreadPoolCallback(void *arg){ }

      nThreadPoolCallback 函数声明为 static 可能是为了将其作用域限制在当前文件内部,避免其它文件中的函数同名冲突,而不是全局作用域的函数。这样做有助于提高代码的可维护性和可读性,因为这个函数只能在当前文件内部被访问和调用,不会被其它文件意外地使用或修改。

  2. 第5节

     struct nWorker *worker = (struct nWorker*) arg;
    

    这行代码创建了一个指向 struct nWorker 结构的指针 worker,并将其初始化为 (struct nWorker*) arg。通常这样的语句在多线程编程中会被用到,其中 arg 是传递给线程的参数,这里将其转换为 struct nWorker* 类型的指针以便在线程中使用。

  3. 第6节

    pthread_cond_signalpthread_cond_broadcast 是 POSIX 线程库中用于线程同步的函数,通常与条件变量(condition variable)一起使用。

    1. pthread_cond_signal 函数用于唤醒一个正在等待条件变量的线程。如果有多个线程正在等待条件变量,那么只会唤醒其中的一个。通常情况下,这是因为某个线程执行了某些操作,使得条件变量的条件满足,因此需要通知等待该条件变量的线程继续执行。
    2. pthread_cond_broadcast 函数用于唤醒所有正在等待条件变量的线程。这个函数会同时唤醒所有等待该条件变量的线程,而不是像 pthread_cond_signal 那样只唤醒其中的一个。通常情况下,这是在某个线程执行了某些操作,使得多个线程都能继续执行时使用。

    这两个函数通常与互斥锁(mutex)一起使用,以实现线程之间的同步。当某个线程需要等待某个条件满足时,它会先释放互斥锁并等待条件变量,而其他线程则可能在条件不满足时进入等待状态。当条件满足时,某个线程会调用 pthread_cond_signalpthread_cond_broadcast 来唤醒等待的线程,让它们继续执行。

1 线程池的使用场景与原理分析

  1. 使用场景:

    1. 百万级的client,server多线程 开线程来同时处理不同client发来的message

      在这里插入图片描述

      but开不了那么多thread,linux下一个posix线程占8M

      1G=1024M开128个最多

      16G内存最多开128*16=2048个thread

    2. 日志文件

      1. disk磁盘操作比memory操作慢不是一个数量级,日志存储到磁盘的文件里,刷新到disk

        处理IO读写,准备好写log里的文字是memory操作,

        log存到文件是disk操作,会引起thread挂起,等IO就绪。 写log任务放到线程池里

  2. 线程池好处

    1. 避免线程太多,内存memory耗尽

    2. 避免反复重复创建和销毁thread, 创建完就放池子,用完还回去

    3. 任务与执行分离(日志写和存储,写内容生成和存到文件)

      例子:银行营业厅,办业务的是任务, 柜员是执行

      在这里插入图片描述

  3. def:

    线程池=

    1. 任务队列
    2. 执行队列
    3. 管理组件 mutex或spinlock加锁 调节任务和执行

2 线程池的结构体定义 threadpool

线程池sdk组件封装software Development Kit

  1. 任务队列:

    任务组成,先定义任务task struct

    再任务队列:链表串起tasks 双向链表

    //1.定义task
    struct nTask{
        void(*task_func)(struct nTask *task);//一个函数指针,指向一个接受 struct nTask* 参数并且没有返回值的函数。这个指针用于表示任务的执行函数。
        void *user data;//一个指向 void 类型的指针,用于存储任务函数可能需要的额外数据或参数。
    
        struct nTask *prev;
        struct nTask *next;
    }; // 双向链表
    

3 线程池的架构分析与实现

1 最底层:系统层,支持层——实现数据结构+宏定义的基本操作

任务队列,执行队列,管理组件

链表(struct)操作:直接用通讯录那一张的宏定义

#define LIST_INSERT(item, list)do{\
    item->prev = NULL;\
    item->next = list;\
    if((list)!= NULL) (list)->prev = item;\
    (list) = item;    \
} while(0)
//二级指针,list要括号(*ppeople)


    
#define LIST_REMOVE(item, list) do {	\
        if (item->prev != NULL) item->prev->next = item->next; \
        if (item->next != NULL) item->next->prev = item->prev; \
        if (list == item) list = item->next;                    \
        item->prev = item->next = NULL;                         \
} while(0)

//1.定义task
struct nTask{
    void(*task_func)(struct nTask *task);
    void *user data;

    struct nTask *prev;
    struct nTask *next;
};

//2.执行
struct nWorker{
    pthread_t threadid;


    struct nWorker *prev;
    struct nWorker *next;
};

//3管理组件 连接worker和task
struct nManager{
    struct nTask *tasks;  //任务队列
    struct nWorker *workers; //执行队列

    pthread_mutex_t mutex; //加互斥锁
    pthread_cond_t cond; //加条件变量,等待满足条件不锁了
};

2 接口层 ,在支持层上包一层

这里管理组件nManager就是threadpool,这里对类型起别名用typedef

4个:创建、销毁、加任务、线程涉及的回调函数

typedef struct nManager{
    struct nTask *tasks;  //任务队列
    struct nWorker *workers; //执行队列

    pthread_mutex_t mutex; //加互斥锁
    pthread_cond_t cond; //加条件变量,等待满足条件不锁了
}ThreadPool;


static void *nThreadPoolCallback(void *arg){
    
}

int nThreadPoolCreate(ThreadPool*pool, int nworker){
    
}

int nThreadPoolDestroy(ThreadPool*pool, int nworker){
    
}

int nThreadPoolPushTask(ThreadPool*pool, struct nTask *task){
    
}

4 线程池初始化实现

多用才能对接口熟悉

函数—— 参数,函数体,返回值

  1. 最终function做成sdk,所以做成API接口给其他人调就行
  2. 初始化struct内四个,除了task
  3. 堆上malloc出来的动态数据,要memset置零,防止内容不确定野指针了
  4. 业务功能(callback)一样,但是实际task任务不同,相当于task是callback的具体实现
// API
int nThreadPoolCreate(ThreadPool*pool, int numWorker){
    if(pool == NULL) return -1;
    if(numWorker < 1) numWorker = 1; //运行线程没有,那就默认1个

    // 2 对struct里4个初始化,task外界扔进来不用
    pthread_cond_t blank_cond = PHTREAD_COND_INITIALIZER; //定义空白锁的条件变量
    memcpy(&pool->cond, &blank_cond,sizeof(pthread_cond_t));//blank_cond 中的 pthread_cond_t 结构体的内容复制到 pool->cond 中。

    pthread_mutex_init(&pool->mutex,NULL);

    int i = 0;
    for(int i =0; i < numWorker; i++){
        struct nWorker *worker = malloc(sizeof(struct nWorker));
        //创建失败
        if(worker ==NULL){
            perror("malloc");
            return -2;
        }
        memset(worker, 0,sizeof(struct worker));
        worker->manager = pool;

        //创建线程
        int ret = pthread_create(worker->threadid, NULL, nThreadPoolCallback, worker); //创建成功返回0,失败1
        if(ret){
            perror("pthread_create");
            free(worker);
            return -3;
        }
        LIST_INSERT(worker, pool->worker);
            
    }
    return 0; //创建成功, callback是业务功能,一样,但是不等同于task任务,但是执行的任务不同
    
}

5 线程池的线程回调函数实现

核心:三件事

判任务队列里有任务

没就等

有就拿出执行,取用户数据

// API
// callback!=task
static void *nThreadPoolCallback(void *arg){
    struct nWorker *worker = (struct nWorker*) arg;
    while(1){
        pthread_mutex_lock(worker->manager->mutex); //对任务加一把锁
        
        while(worker->manager->tasks == NULL){//判有任务,没就等,有就拿出执行,取用户数据
            pthread_cond_wait(&worker->manager->cond, &worker->manager->mutex);
            
        }
        struct nTask *task = worker->manager->tasks;
        LIST_REMOVE(task, worker->manager->tasks); //把任务队列tasks的首节点task执行完了,移出来
        
        pthread_mutex_unlock(worker->manager->mutex);

        task->task_func(task->user_data);
    }
    free(worker);// but没有退出的break的地方,struct nWorker里引入终止标识    
}

问题:but没有退出的break的地方,struct nWorker里引入终止标识

//2.执行
struct nWorker{
    pthread_t threadid;
    int terminate;
    
    struct nManager *manager; //worker需要有manager联系方式


    struct nWorker *prev;
    struct nWorker *next;
};

同时

static void *nThreadPoolCallback(void *arg){
    struct nWorker *worker = (struct nWorker*) arg;
    while(1){
        pthread_mutex_lock(worker->manager->mutex); //对任务加一把锁
        
        while(worker->manager->tasks == NULL){//判有任务,没就等,有就拿出执行,取用户数据
            if(worker->terminate) break; //是1就是终止
            pthread_cond_wait(&worker->manager->cond, &worker->manager->mutex);
            
        }

        if(worker->terminate){
            // 退出最外层while,先解锁,不然可能死锁了
            pthread_mutex_unlock(worker->manager->mutex); 
            break; 
        }
        struct nTask *task = worker->manager->tasks;
        LIST_REMOVE(task, worker->manager->tasks); //把任务队列tasks的首节点task执行完了,移出来
        
        pthread_mutex_unlock(worker->manager->mutex);

        task->task_func(task->user_data);
    }
    free(worker);// but没有退出的break的地方,struct nWorker里引入终止标识    
}

6 线程池的任务添加与线程池销毁

terminate置1就退出来了

int nThreadPoolDestroy(ThreadPool*pool, int nworker){
    struct nWorker *worker = NULL;

    for(worker = pool->workers; worker != NULL; worker = worker->next){
        worker->terminate;//都置1
    }

    //信号什么时候往下走,广播使所有条件满足让信号往下走
    pthread_mutex_lock(&pool->mutex);
    pthread_cond_broadcast(&pool->cond);// 唤醒所有广播和等待用的同一把锁,不会有死锁,什么东西没听懂
    pthread_mutex_unlock(&pool->mutex);

    pool->workers= NULL;
    pool->tasks = NULL;
    return 0;
}

任务添加

int nThreadPoolPushTask(ThreadPool*pool, struct nTask *task){
    //通知thread有task来了
    pthread_mutex_lock(&pool->mutex);
    LIST_INSERT(task, pool->tasks);

    //通知条件变量可满足,唤醒一个thread
    pthread_cond_signal(&pool->cond);
    
    pthread_mutex_unlock(&pool->mutex);
    
}

7 线程池代码gdb调试与bug修改

gcc -o threadpool threadpool.c -lpthread

一堆错 有问题, 视频里面没有写main后面的函数!! 根本看不懂了,这里后面没法调



//
// sdk --> debug thread pool

#if 1

#define THREADPOOL_INIT_COUNT	20
#define TASK_INIT_SIZE			1000


void task_entry(struct nTask *task) { //type 

	//struct nTask *task = (struct nTask*)task;
	int idx = *(int *)task->user_data;

	printf("idx: %d\n", idx);

	free(task->user_data);
	free(task);
}


int main(void) {

	ThreadPool pool = {0};
	
	nThreadPoolCreate(&pool, THREADPOOL_INIT_COUNT);
	// pool --> memset();
	
	int i = 0;
	for (i = 0;i < TASK_INIT_SIZE;i ++) {
		struct nTask *task = (struct nTask *)malloc(sizeof(struct nTask));
		if (task == NULL) {
			perror("malloc");
			exit(1);
		}
		memset(task, 0, sizeof(struct nTask));

		task->task_func = task_entry;
		task->user_data = malloc(sizeof(int));
		*(int*)task->user_data  = i;

		
		nThreadPoolPushTask(&pool, task);
	}

	getchar();
	
}


#endif

gdb调试,适合小工程

gcc -o threadpool threadpool.c -lpthread -g
gdb ./threadpool

打断点:

  1. 在判断的地方加breakpoint,比如while if

    有可能出现空指针

    b 行数
    b 64 (while判断)
    b 76 (list remove)
    b 115 (list insert)
    r(就是run)
    c(continue) 没有出现视频里的问题
    

    nThreadPoolCreate里少 memset(pool, 0, sizeof(ThreadPool));

     b 80 (task->task_func)
     b 201(pushtask)
     r
     c
     c
    

    报错了 并没有解决了,还是segmentation fault

    Thread 3 "threadpool" received signal SIGSEGV, Segmentation fault.
    [Switching to Thread 0x7ffff6fee700 (LWP 12096)]
    0x0000000000400f08 in task_entry (task=0x604a80) at threadpool.c:170
    170		int idx = *(int *)task->user_data;
    

    太丑了,放弃了,sourceinsight长得太丑了,还卡的一批,用vscode连虚拟机ok了

    这节课基本没听懂!!!云里雾里乱起八糟的

    最后调出来了是这个问题

    nThreadPoolCallback(void *arg)里面的task->task_func(task->user_data);改成 task->task_func(task);

  • 30
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值