Pawan Adhikari Pawan Adhikari - 3 months ago 10
C Question

Regarding reentrancy in C

If you have a function from a library f_func() and you know it's not re-entrant. How would you use it in a threaded environment (POSIX)? You can't access the source code of the library.

Answer

You can wrap it in a mutex. Here is an example usage:

pthread_mutex_t f_func_mutex = PTHREAD_MUTEX_INITIALIZER;

pthread_mutex_lock(&f_func_mutex);

f_func();

// if f_func has "side effects", such as setting a global, you'll want to grab
// the value within the locked region:
int local = global_set_by_f_func;

pthread_mutex_unlock(&f_func_mutex);
Comments