hi,
quite new programming threads , have doubt can not solve myself. want ensure variables protected correctly using mutex system. taking next code example:
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.
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); }
, also, if need read value without modifying it, need lock , unlock variable?
many help.
both, otherwise have no protection.juranga wrote:the variable modified 2 threads, should protect using mutex. but, have protect in both threads? mean, not protecting in 1 thread enough?
depends. if thread modify ever stores intermediate result in it, yes should lock , unlock. egjuranga wrote:and also, if need read value without modifying it, need lock , unlock variable?
code: select all
lock(mutex); temperature = read_temperature_c(); temperature *= 1.8; temperature += 32; unlock(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
Post a Comment