线程池之c语言实现

本文探讨了如何使用C语言实现线程池,重点介绍了线程池的关键技术,包括链表、线程间的同步互斥以及函数指针的应用。作者提供了自己编写的代码,并确保其已成功编译和运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在新浪博客里面提到了几点线程池的关键技术:1. 链表  2. 线程间的同步互斥 3. 函数指针

今天我们来实现一把。


下面的代码都是自己抽空写的,编译运行过。

list.h

#ifndef _list_h
#define _list_h

#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

//#define IF_LOCK_LIST 0

struct s_dlist_node {
	struct s_dlist_node *pre;
	struct s_dlist_node *next;
	void *data;
};

struct s_dlist {
	struct s_dlist_node *head;
	pthread_mutex_t pth_mutex;
	int s_dlist_len;
};



struct s_dlist *dlist_create();

struct s_dlist_node *dlist_node_create(void *data);

bool dlist_insert_ahead(struct s_dlist *dlist, void *data);

struct s_dlist_node *dlist_pop_last(struct s_dlist *dlist);

bool dlist_isempty(struct s_dlist *dlist);
#endif

list.cpp

#include "list.h"

struct s_dlist_node *dlist_node_create(void *data)
{
	struct s_dlist_node *node = 
		(struct s_dlist_node *)malloc(sizeof(struct s_dlist_node));
	if (node == NULL) {
		return NULL;
	}
	node->pre = NULL;
	node->next = NULL;
	node->data = data;

	return node;
}

bool dlist_free(struct s_dlist *dlist)
{
	struct s_dlist_node *node;
	while (!dlist_isempty(dlist)) {
		node = dlist_pop_last(dlist);
		printf("get a num from list:%d\n", *(int *)(node->data));
		free(node);
	}
	free(dlist->head);
	free(dlist);
	return true;
}

struct s_dlist *dlist_create()
{
	struct s_dlist *dlist = 
		(struct s_dlist *)malloc(sizeof(struct s_dlist));
	if (dlist == NULL) {
		return NULL;
	}

	struct s_dlist_node *head = dlist_node_create(NULL);
	head->p
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值