linux下线程同步

35 篇文章 0 订阅

这里我做的测试使用的模型是生产者消费者模型,分成两种情况

其一只有一个缓冲区,我们使用信号量即可,分成两个,empty  和full。当缓冲区有空时,则生产者生产,当缓冲区full时。消费者消费

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
#include<semaphore.h>
//生产者消费者模式,只有一个缓冲区,一个消费者一个生产者
//使用信号量进行线程同步
void* consumer(void* arg);
void* producer(void* arg);
int gBuffer=0;
sem_t empty={0};
sem_t full={0};
int main()
{
	pthread_t c_th={0};
	pthread_t p_th={0};
	int c_res=0;
	int p_res=0;
	sem_init(&empty,0,1);
	sem_init(&full,0,0);
	c_res=pthread_create(&c_th,NULL,consumer,(void*)&gBuffer);
	if(0!=c_res)
	{
		printf("消费者线程创建失败\n");
		exit(0);
	}
	p_res=pthread_create(&p_th,NULL,producer,(void*)&gBuffer);
	if(0!=p_res)
	{
		printf("生产者线程创建失败\n");	
		exit(0);
	}
	void* c_rtl=NULL;
	c_res=pthread_join(c_th,&c_rtl);
	if(0!=c_res)
	{
		printf("消费者线程 pthread_join 失败\n");
		exit(0);
	}
	void* p_rtl=NULL;
	p_res=pthread_join(p_th,&p_rtl);
	if(0!=p_res)
	{	
		printf("生产者 pthread_join 失败\n");
		exit(0);
	}
	sem_destroy(&full);
	sem_destroy(&empty);
	return 0;
}
void * consumer(void* arg)
{
	int nCount=0;
	while(1)
	{
		sem_wait(&full);
		printf("consumer 成功\n");
		sem_post(&empty);
		nCount++;
		if(50==nCount)
			break;
	}
	pthread_exit(0);
}
void * producer(void* arg)
{
	int nCount=0;
	while(1)
	{
		sem_wait(&empty);
		printf("producer 成功\n");
		sem_post(&full);
		nCount++;
		if(50==nCount)
			break;
	}
	pthread_exit(0);
}

当存在多个缓冲区的时候,则除却信号量标记,缓冲区状态的时候,还要为每个缓冲区分配互斥变量,同一时刻,一个缓冲区只能被一个线程访问,无论是生产者还是消费者

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
#include<semaphore.h>
//生产者消费者模式,多个缓冲区,多个生产者
//使用信号量进行线程同步
void* consumer(void* arg);
void* producer(void* arg);
int gBuffer[4]={0};
int buf_count=4;
//为每个缓冲区都准备一个互斥变量,同一时间只能有一个线程进行访问
pthread_mutex_t mutex[4]={0};
sem_t empty={0};
sem_t full={0};
int main()
{
	pthread_t c_th={0};
	pthread_t p_th={0};
	int c_res=0;
	int p_res=0;
	sem_init(&empty,0,4);
	sem_init(&full,0,0);
	int i=0;
	for(;i<buf_count;i++)
	{
		pthread_mutex_init(&mutex[i],NULL);
	}
	c_res=pthread_create(&c_th,NULL,consumer,(void*)&gBuffer);
	if(0!=c_res)
	{
		printf("消费者线程创建失败\n");
		exit(0);
	}
	p_res=pthread_create(&p_th,NULL,producer,(void*)&gBuffer);
	if(0!=p_res)
	{
		printf("生产者线程创建失败\n");	
		exit(0);
	}
	void* c_rtl=NULL;
	c_res=pthread_join(c_th,&c_rtl);
	if(0!=c_res)
	{
		printf("消费者线程 pthread_join 失败\n");
		exit(0);
	}
	void* p_rtl=NULL;
	p_res=pthread_join(p_th,&p_rtl);
	if(0!=p_res)
	{	
		printf("生产者 pthread_join 失败\n");
		exit(0);
	}
	sem_destroy(&full);
	sem_destroy(&empty);
	for(i=0;i<buf_count;i++)
	{
		pthread_mutex_destroy(&mutex[i]);
	}
	return 0;
}
void * consumer(void* arg)
{
	int nCount=0;
	int i=0;
	while(nCount<=20)
	{
		sem_wait(&full);
		for(i=0;i<buf_count;i++)			
		{
			if(1==gBuffer[i])
			{
				pthread_mutex_lock(&mutex[i]);
				gBuffer[i]=0;
				printf("缓冲区%d归0\n",i);		
				pthread_mutex_unlock(&mutex[i]);
				sem_post(&empty);
				nCount++;
			}
		}
	}
	pthread_exit(0);
}
void * producer(void* arg)
{
	int nCount=0;
	int i=0;
	while(nCount<=20)
	{
		sem_wait(&empty);
		for(i=0;i<buf_count;i++)
		{
			if(gBuffer[i]==0)
				{
					pthread_mutex_lock(&mutex[i]);
					gBuffer[i]=1;
					printf("缓冲区%d置位\n",i);
					pthread_mutex_unlock(&mutex[i]);
					sem_post(&full);
					nCount++;
				}
		}		
	}
	pthread_exit(0);
}

跟上一篇一样,说下 makefile的内容,多了一个  -lrt

test: thread.o
	gcc -o test thread.o  -lpthread  -lrt
thread.o:thread.c
	gcc -c thread.c
clean:
	rm test *.o



  • 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
发出的红包

打赏作者

世纪殇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值