Communication between Two threads in pthread

14,622

Solution 1

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.

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.

Solution 2

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.

Share:
14,622
duslabo
Author by

duslabo

I am an engineer. Link to git

Updated on June 05, 2022

Comments

  • duslabo
    duslabo almost 2 years

    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?