Linux下线程池的代码

此博客仅为了存放代码。(Linux,加锁,线程池)

头文件:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <sys/mman.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <ctype.h>
#include <string.h>

#define	_PORT		8000
#define	_BUF_SIZE	1500
#define	_LISTEN		128
#define	TRUE	1
#define	FALSE	0
#define	CREATE_DES	10


/*Task Queue*/
typedef struct
{
	void * (*task)(void*);
	void * arg;
}task_t;
/*Thread pool*/
typedef struct
{
	pthread_mutex_t pool_lock;
	pthread_mutex_t arg_lock;
	pthread_cond_t not_full;
	pthread_cond_t not_empty;
	pthread_t * threads; //(pthread_t *)malloc(max*(pthread_t))
	pthread_t Manager_tid;
	task_t * task_queue;
	int pool_min;
	int pool_max;
	int alive;
	int busy;
	int queue_front;
	int queue_rear;
	int queue_max;
	int queue_size;
	int pool_shutDown;
	int wait;
}pool_t;

/*Function*/
//1.创建线程池
pool_t * Pool_Create(int , int ,int);
//2.生产者工作
int Pool_Add_TaskQueue(pool_t *,void*(*)(void * ),void * );
//3.消费者
int Pool_Def_Task(pool_t * ,)
	/*
		上锁
		如果当前队列任务为0,并且线程池开关未关闭,消费者阻塞
		如果线程池开关为关闭,销毁线程池
		判断wait 回收数量如果大于0,结束自身线程,wait--;
		从头索引出队
		重新计算头索引 pool->queue_front = (pool->queue_front+1)%pool->queue_max;
		当前队列任务数减1 ,pool->queue_size--;
		唤醒一个生产者 pthread_cond_signal(&pool->not_full);
		执行用户工作
		解锁
		

	*/
//4.用户工作
//5.管理者工作
	/*
			周期性检测线程池情况,统计线程池数据
			试探存活线程数
			计算扩容与缩减
			
		
	*/

.c文件:

#include <thread_pool.h>
pool_t * Pool_Create(int thread_min , int thread_max , int queue_max)
{
		pool_t * pool = NULL;
		int i=0;
		if((pool = (pool_t * )malloc(sizeof(pool_t)))==NULL)
		{
				perror("Pool_Create() pool Malloc:");
				return NULL;
		}
		pool->pool_min = thread_min;
		pool->pool_max = thread_max;
		pool->alive = 0;
		pool->busy = 0;
		pool->queue_front = 0;
		pool->queue_rear = 0;
		pool->queue_max = queue_max;
		pool->queue_size = 0;
		pool->pool_shutDown = TRUE;
		if((pool->threads = (pthread_t *)malloc(thread_max * sizeof(pthread_t)))==NULL)
		{
				perror("Pool_Create() threads Malloc:");
				return NULL;
		}
		memset(pool->threads,0,thread_max * sizeof(pthread_t));
		if((pool->task_queue = (task_t *)malloc(queue_max * sizeof(task_t)))==NULL)
		{
				perror("Pool_Create() task_queue Malloc:");
				return NULL;
		}
		if(pthread_mutex_init(&pool->pool_lock,NULL)!=0||pthread_mutex_init(&pool->arg_lock,NULL)!=0||pthread_cond_init(&pool->not_full)!=0||pthread_cond_init(&pool->not_empty)!=0)
		{
				perror("Pool_Create() init Mutex or Cond:");
				return NULL;
		}
		for(i;i<CREATE_DES;i++){
				pthread_create(&pool->threads[i],NULL,(消费者工作),(传参));
		}
		pthread_create(&pool->Manager_tid,NULL,(管理者工作),(传参));
		return pool;
}
int Pool_Add_TaskQueue(pool_t * pool,void * (*Work)(void*arg),void*arg)
{
		//1.判断生产者是否需要阻塞
		pthread_mutex_lock(pool->pool_lock);
		while(pool->queue_size == pool->queue_max && pool->pool_shutDwon==TRUE){
				pthread_cond_wait(&pool->not_full,&pool->pool_lock);

		}
		if(pool->pool_shutDown == FALSE){
						pthread_mutex_unlock(&pool->pool_lock);
						/*退出处理*/
		}
		/*不一定行不行?*/
		if(pool->task_queue[pool->queue_rear].arg != NULL){
			free(pool->task_queue[pool->queue_rear].arg);
			pool->task_queue[pool->queue_rear] = NULL;
		}
		/*将任务添加到队列尾端*/
		pool->task_queue[pool->queue_rear].task = Work;
		pool->task_queue[pool->queue_rear].arg = arg;
		/*计算队列*/
		pool->queue_rear = (pool->queue_rear+1)%pool->queue_max;
		pool->queue_size++;
		/*唤醒一个消费者*/
		pthread_cond_signal(&pool->not_empty);
		/*解锁*/
		pthread_mutex_unlock(&pool->pool_lock);
		return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Linux系统下,可以使用线程实现串口通信例程。 首先,需要引入一些头文件,如`<stdio.h>, <stdlib.h>, <unistd.h>, <fcntl.h>, <termios.h>, <pthread.h>`,以便使用相关函数和数据结构。 接下来,打开串口设备文件,使用`open()`函数,并通过`<fcntl.h>`中的`O_RDWR`参数设置为可读写模式。例如,打开`/dev/ttyS0`串口设备: ```c int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY); if (fd == -1) { perror("打开串口失败"); exit(EXIT_FAILURE); } ``` 然后,配置串口属性,包括波特率、数据位、停止位等。首先需要获取当前串口属性,使用`tcgetattr()`函数,并通过`<termios.h>`中的数据结构`struct termios`进行配置。例如,设置波特率为115200: ```c struct termios attr; if (tcgetattr(fd, &attr) == -1) { perror("获取串口属性失败"); close(fd); exit(EXIT_FAILURE); } cfsetispeed(&attr, B115200); cfsetospeed(&attr, B115200); if (tcsetattr(fd, TCSANOW, &attr) == -1) { perror("设置串口属性失败"); close(fd); exit(EXIT_FAILURE); } ``` 接下来,创建一个线程,用于接收串口数据。使用`pthread_create()`函数,并编写线程函数。例如,以下为接收串口数据的线程函数: ```c void *receiveThread(void *arg) { char buffer[256]; int len; while (1) { len = read(fd, buffer, sizeof(buffer)); if (len > 0) { // 处理接收到的数据 // ... } } return NULL; } pthread_t tid; pthread_create(&tid, NULL, receiveThread, NULL); ``` 最后,主线程(或其他线程)可以通过`write()`函数向串口发送数据。例如,向串口发送一个字符串: ```c char *str = "Hello, Serial!"; write(fd, str, strlen(str)); ``` 整个程序运行时,主线程可以继续执行其他任务,而串口数据的接收则在单独的线程中进行。 这样,就完成了一个简单的Linux下线程实现串口通信的例程。 ### 回答2: 在Linux下,可以通过使用线程来实现串口通信。下面是一个简单的示例代码: ```c #include <stdio.h> #include <fcntl.h> #include <termios.h> #include <unistd.h> #include <pthread.h> int fd; // 串口文件描述符 pthread_t thread_id; // 线程ID void* read_thread(void* arg) { char buf[255]; while(1) { int len = read(fd, buf, sizeof(buf)); // 从串口读取数据 if (len > 0) { buf[len] = '\0'; // 添加字符串结束符 printf("接收到的数据: %s\n", buf); } } } int main() { // 打开串口 fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1) { printf("无法打开串口\n"); return -1; } // 配置串口 struct termios options; tcgetattr(fd, &options); cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); tcsetattr(fd, TCSANOW, &options); // 创建读取数据的线程 pthread_create(&thread_id, NULL, read_thread, NULL); // 主线程继续执行其他任务 while(1) { // 发送数据到串口 char msg[] = "Hello, Serial Port!"; write(fd, msg, sizeof(msg)); usleep(1000000); // 等待1秒 } // 关闭串口 close(fd); return 0; } ``` 在上述代码中,通过`open`函数打开了串口设备文件`/dev/ttyS0`(请根据实际情况更改),然后使用`termios`结构体配置了串口的波特率、数据位、停止位等属性。接下来,通过`pthread_create`函数创建了一个线程,该线程负责读取串口数据。主线程则负责发送数据到串口。 需要注意的是,该例程只是一个简单的示例,仅用于说明线程实现串口通信的基本思路。实际应用中,还需考虑数据的解析、错误处理、线程同步等问题。 ### 回答3: 在Linux下,可以使用串口通信库来实现线程的串口通信例程。下面是一个简单的例子: 1. 首先,我们需要安装和配置串口通信库。常用的库包括`libserialport`和`termios`。你可以使用包管理工具来安装这些库。 2. 在程序中,我们需要引入相关的头文件和库: ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <serialport.h> ``` 3. 然后,创建一个线程来读取串口数据。可以定义一个函数作为线程入口点,例如`serial_read`: ``` void *serial_read(void *data) { struct sp_port *serial_port = (struct sp_port *)data; char buffer[256]; int n; while (1) { n = sp_blocking_read(serial_port, buffer, sizeof(buffer), 100); if (n > 0) { // 处理接收到的数据 printf("Received: %.*s\n", n, buffer); } else { // 读取数据出错或超时 printf("Serial read error or timeout\n"); } } return NULL; } ``` 4. 接下来,创建一个线程来发送串口数据。可以定义一个函数作为线程入口点,例如`serial_write`: ``` void *serial_write(void *data) { struct sp_port *serial_port = (struct sp_port *)data; char message[] = "Hello, Serial Port!\n"; while (1) { sp_nonblocking_write(serial_port, message, sizeof(message) - 1); usleep(1000000); // 暂停1秒钟 } return NULL; } ``` 5. 在主函数中,打开串口设备并创建两个线程: ``` int main() { struct sp_port *serial_port; pthread_t read_thread, write_thread; // 打开串口设备(例如:/dev/ttyS0) sp_get_port_by_name("ttyS0", &serial_port); sp_open(serial_port, SP_MODE_READ_WRITE); // 创建读取线程 pthread_create(&read_thread, NULL, serial_read, (void *)serial_port); // 创建写入线程 pthread_create(&write_thread, NULL, serial_write, (void *)serial_port); // 等待线程结束 pthread_join(read_thread, NULL); pthread_join(write_thread, NULL); // 关闭串口设备 sp_close(serial_port); sp_free_port(serial_port); return 0; } ``` 这是一个简单的例程,通过两个线程实现了线程的串口通信。读取线程通过不断调用`sp_blocking_read`函数读取串口数据,而写入线程通过不断调用`sp_nonblocking_write`函数发送串口数据。你可以根据需求来修改和扩展这个例程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值