Linux pthread中两个线程之间的通信

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10868678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:38:09  来源:igfitidea点击:

Communication between Two threads in pthread

clinuxmultithreadingpthreadsposix

提问by duslabo

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?

我正在创建两个线程 thread1 和 thread2。线程 1 正在读取模拟值,线程 2 应处理在线程 1 中读取的模拟值并设置 PWM 参数。到目前为止我所做的是,在主文件(我正在创建线程的地方)中,我已经声明了一个全局变量(用于存储模拟值)并将指向全局变量的指针传递给两个线程。在线程 1 中读取的模拟值存储在全局变量中,在线程 2 中读取全局变量并对其进行处理。所以,我的问题是有没有其他方法可以做到这一点?即我们有最适合此应用程序的信号量、互斥锁等?

采纳答案by Jens Gustedt

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

您的问题没有通用答案,这取决于您的很多用例。

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.

pthreads 的经典方法是使用互斥-条件对向读取线程发送值的修改信号。这适用于该线程大部分处于空闲状态并且只需要进行更改的情况。在这里,除了互斥锁之外的条件变量将确保您的阅读线程不会在他无所事事的情况下吃资源。

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.

如果您的读取线程正在做一些永久性的工作并且只需要使用该值,则有不同的情况:第一种是使用互斥锁保护变量,只是为了确保您读取的值不会中途更新并且那样总是一致的。

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.

更现代的方法是使用(或确保)您的读写操作是原子的。C11 是新的 C 标准,为此提供了接口,大多数编译器已将此类操作作为扩展实现。

回答by nav_jan

I think this will need a very basic mutex . See my pseudo code below :

我认为这将需要一个非常基本的互斥锁。请参阅下面的我的伪代码:

Thread1() {
    Mutex_lock();
    Process global variable;
    Unlock_mutex();
}

Similar thread2.. I can provide more specific answer if you provide your current code.

类似的 thread2 .. 如果您提供当前的代码,我可以提供更具体的答案。