c - Thread concurrency in linux -
i beginner so, please let me know if question not clear.
i using 2 threads example , b. , have global variable 'p'. thread while looping , incrementing value of 'p'.at same time b trying set 'p' other value(both 2 different thread functions).
if using mutex synchronizations, , thread mutex , incrementation 'p' in while loop,but not release mutex. question if thread doesn’t release mutex can thread b access variable 'p'??
edit thread b protected accses 'p' using mutex.
if thread lock using pthread_mutex_lock(), , doesn’t release , happen if same thread(a) try access lock again(remember thread while looping) example
while(1) { pthread_mutex_lock(&mutex); p = 10; }
is there problem code if mutex never released?
simple example of statically initialized mutex
#include <pthread.h> #include <stdio.h> #include <stdlib.h> static int p = 0; static pthread_mutex_t locker = pthread_mutex_initializer; static void * threadfunc(void *arg) { int err; err = pthread_mutex_lock(&locker); if (err != 0){ perror("pthread_mutex_lock failed"); exit(1); } p++; err = pthread_mutex_unlock(&locker); if (err != 0){ perror("pthread_mutex_unlock failed"); exit(1); } return null; } int main(int argc, char *argv[]) { pthread_t a, b; pthread_create(&a, null, threadfunc, null); pthread_create(&b, null, threadfunc, null); pthread_join(a, null); pthread_join(b, null); printf("p = %d\n", p); return 0; }
error checking in main omitted brevity should used. if not release mutex program never finish, thread b never lock.
Comments
Post a Comment