【C语言实现串口通信知识点整理(一)】线程、打开串口、设置波特率、设置校验位、互斥锁等实现基本的通信

 

部分代码借鉴地址:https://blog.csdn.net/wangqingchuan92/article/details/73497354/ 谢谢!

1.创建线程在线程内进行串口之间的收发

void CREAT_pthread(void)
{
	pthread_t t0;

	//创建线程1
	if(pthread_create(&t0, NULL, print_a, NULL) == -1){
		puts("fail to create pthread t0");
		exit(1);
	}else
		{
			printf("\n\nt0 create success!!!");
		}
}

遇到的问题:在一开始创建线程的时候,调用了pthread_join()函数,主线程需要等子线程完成操作后才会执行。由于子线程是电视开机后一直在执行,随时会接收数据发送数据,因此导致主线程没办法执行,电视死机没办法正常操作。

    // 等待线程结束
    void * result;
    if(pthread_join(t0, &result) == -1){
        puts("fail to recollect t0");
        //exit(1);
    }

    if(pthread_join(t1, &result) == -1){
        puts("fail to recollect t1");
       // exit(1);
    }

2.打开串口

 int OpenDev(char *Dev)
 {
	 int fd = open(Dev,O_RDWR | O_NOCTTY | O_NONBLOCK);
	 if(-1 == fd)
	 {
		 per
  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个使用互斥锁和条件变量实现线程通信的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define BUFFER_SIZE 10 int buffer[BUFFER_SIZE]; // 共享缓冲区 int count = 0; // 缓冲区中元素个数 pthread_mutex_t mutex; // 互斥锁 pthread_cond_t cond; // 条件变量 void *producer(void *arg) { int item = 0; while (1) { pthread_mutex_lock(&mutex); // 加锁 if (count == BUFFER_SIZE) { // 缓冲区已满,等待消费者消费 pthread_cond_wait(&cond, &mutex); } buffer[count++] = item++; // 生产一个物品,放入缓冲区 printf("Producer produces item %d\n", item); pthread_mutex_unlock(&mutex); // 解锁 pthread_cond_signal(&cond); // 唤醒一个等待的消费者 } pthread_exit(NULL); } void *consumer(void *arg) { int item = 0; while (1) { pthread_mutex_lock(&mutex); // 加锁 if (count == 0) { // 缓冲区为空,等待生产者生产 pthread_cond_wait(&cond, &mutex); } item = buffer[--count]; // 消费一个物品,从缓冲区中取出 printf("Consumer consumes item %d\n", item); pthread_mutex_unlock(&mutex); // 解锁 pthread_cond_signal(&cond); // 唤醒一个等待的生产者 } pthread_exit(NULL); } int main() { pthread_t producer_tid, consumer_tid; // 初始化互斥锁和条件变量 pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); // 创建生产者和消费者线程 pthread_create(&producer_tid, NULL, producer, NULL); pthread_create(&consumer_tid, NULL, consumer, NULL); // 等待线程结束 pthread_join(producer_tid, NULL); pthread_join(consumer_tid, NULL); // 销毁互斥锁和条件变量 pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; } ``` 在上面的示例代码中,我们使用了一个缓冲区来实现生产者和消费者之间的通信。生产者将生产的物品放入缓冲区,消费者从缓冲区中取出物品进行消费。当缓冲区已满时,生产者会等待消费者消费;当缓冲区为空时,消费者会等待生产者生产。在等待的过程中,使用条件变量来进行线程的阻塞和唤醒。当生产者放入一个物品时,会唤醒一个等待的消费者;当消费者取出一个物品时,会唤醒一个等待的生产者。同时,使用互斥锁来保护共享缓冲区的访问,确保线程安全。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值