在pthread的两个线程间的通信 [英] Communication between Two threads in pthread

查看:120
本文介绍了在pthread的两个线程间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个线程线程1和线程。线程1读取模拟值1和线程将处理该读线程1,并设置PWM参数的模拟值。我做了什么到现在就是在主文件(其中我创建的线程),我宣布一个全局变量(存储模拟值),并通过该指针全局变量来两个线程。在线程1中的读出模拟值在全局变量和在线程2存储读取全局变量和处理它。所以,我的问题是有没有另一种方式来做到这一点?即我们有信号灯,互斥等,这是最适合这种应用?

I am creating two threads thread1 and thread2. Thread1 is reading the Analog value and thread2 shall process the analog value which is read in thread1 and sets the PWM arguments. what I have done till now is, in main file ( where I am creating threads) I have declared a global variable ( to store the analog value) and passing the pointer to the global variable to both the threads. In thread1 the the read analog value storing in the global variable and in thread2 reads the global variable and processing it. So, my question is is there any another way to do this ? i.e. we have semaphore, mutex etc which is best suitable for this application?

推荐答案

有没有一般回答你的问题,它取决于很多您的使用情况。

There is no general answer to your question, it depends a lot of your use case.

对于pthreads经典方法是使用一个互斥条件对信号的值来读出的线程的变形例。该线程大多处于闲置状态,并只工作在一个变化做这将是适当的情况下。在这里,除了互斥条件变量将确保当他无关,你的阅读线程不会吃资源。

The classic method for pthreads would be to use a mutex-condition pair to signal a modification of the value to the reading thread. This would be appropriate for the case that that thread mostly is idle and has only work to do on a change. Here, a condition variable in addition to the mutex would ensure that your reading thread would not eat resources while he has nothing to do.

如果你的阅读线程正在做一些永久性的工作,刚刚使用的值有不同的方案:第一是保护变量用互斥锁,只是为了确保您阅读价值不半方式更新,通过始终保持一致。

If your reading thread is doing some permanent work and has just to use the value there are different scenarios: the first would be to protect the variable with a mutex, just to make sure that the value that you read is not half-way updated and by that is always consistent.

一个更现代的方法是使用(或保证)您读取和写入操作都是原子。 C11,新的C标准,提供接口对于大多数编译器已经实现了这样的操作的扩展。

A more modern approach would be to use (or ensure) that your read and write operations are atomic. C11, the new C standard, provides interfaces for that and most compilers implement such operations already as extensions.

这篇关于在pthread的两个线程间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆