Let's say I have a thread pool that has 5 child threads. And they are calling a function called "functionA()" How do I make the function to be thread safe?
Also if those 5 threads are called at the same time then are they executed concurrently? or do they wait until a thread that currently works in the function to be finished ?
Thanks in advance..
Making a function threadsafe In multithreaded programs, all functions called by multiple threads must be threadsafe. However, a workaround exists for using thread-unsafe subroutines in multithreaded programs. Non-reentrant functions usually are thread-unsafe, but making them reentrant often makes them threadsafe, too.
write() is certainly thread-safe. The problem is that a partial write() could require multiple calls in order to completely write the data, and while that is "thread-safe" it could result in interleaved data.
the standard C printf() and scanf() functions use stdio so they are thread-safe.
In C, local static variables are initialized in a thread-safe manner because they're always initialized at program startup, before any threads can be created. It is not allowed to initialize local static variables with non-constant values for precisely that reason.
A function is already thread safe if it doesn't modify non-local memory and it doesn't call any function that does. In this (trivial) case, you don't have to do anything.
You really want to think about protecting data, not functions. For example, let's say that the function modifies non-local data structure X. Provide a mutex to protect X and lock it before each access and unlock it after. You may have more than one function that accesses X (e.g. insertX(), deleteX(), ...). As long as you protect the data you'll be OK.
Using a mutex you can do that.
either:
mutex_lock(&mutex);
functionA();
mutex_unlock(&mutex);
or inside functionA();
int functionA() {
mutex_lock(&mutex);
// code
mutex_unlock(&mutex);
}
careful with the second solution, because if the function has other exit paths (a return in the middle for example) and the mutex in not unlocked, you have a situation called deadlock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With