Mutex in Threads - Raspberry Pi Forums


hi,

quite new programming threads , have doubt can not solve myself. want ensure variables protected correctly using mutex system. taking next code example:

code: select all

#include <pthread.h>  #include <stdio.h>  #define num_threads     5  int = 1;   void *printhello(void *)  {     a++;     pthread_exit(null);  }   int main (int argc, char *argv[])  {     pthread_t thread;     int rc;      printf("in main: creating thread %ld\n", t);     rc = pthread_create(&threads, null, printhello, null);     if (rc){           printf("error; return code pthread_create() %d\n", rc);           exit(-1);        }      for(int h=0; h<20;h++)         a++;     }      /* last thing main() should */     pthread_exit(null);  }
variable modified 2 threads, should protect using mutex. but, have protect in both threads? mean, not protecting in 1 thread enough?

, also, if need read value without modifying it, need lock , unlock variable?


many help.

juranga wrote:the variable modified 2 threads, should protect using mutex. but, have protect in both threads? mean, not protecting in 1 thread enough?
both, otherwise have no protection.
juranga wrote:and also, if need read value without modifying it, need lock , unlock variable?
depends. if thread modify ever stores intermediate result in it, yes should lock , unlock. eg

code: select all

lock(mutex); temperature = read_temperature_c(); temperature *= 1.8; temperature += 32; unlock(mutex);
yes you'd want lock , unlock in reader thread, otherwise result after multiplication before addition. wouldn't crazy enough write above code, there conditions might want store intermediate , safe accesses being behind mutex.

example of ok not lock, @ https://github.com/raspberrypi/userland ... al_queue.c
queue->length ever manipulated atomic operations (eg ++ or --), safe in mmal_queue_length read without acquiring mutex.


raspberrypi



Comments