Sunday, 15 April 2012

c - How to prevent a thread to enter in a function if there is already one in? -



c - How to prevent a thread to enter in a function if there is already one in? -

i have function (my_func) can called programme has multiple thread. , don't want function executed twice or more in same time. because i'm writing in memory, , don't want them write in same time.

void my_func() { // want line blocks execution if 1 still pending /* code here */ }

use mutex lock @ origin of function , mutex unlock before going out function

pthread_mutex_t my_func_mutex = pthread_mutex_initializer; void my_func() { pthread_mutex_lock(&my_func_mutex); // @ origin of function ..... pthread_mutex_unlock(&my_func_mutex); // not forget unlock mutex before going out function }

you can in other way if want:

pthread_mutex_t my_func_mutex = pthread_mutex_initializer; #define my_func_macro() \ { \ pthread_mutex_lock(&my_func_mutex); \ my_func(); \ pthread_mutex_unlock(&my_func_mutex); \ } while(0) void my_func() { ..... }

and in code phone call my_func_macro() instead of my_func()

c multithreading pthreads

No comments:

Post a Comment