Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a function thread safe in C++? [closed]

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..

like image 529
codereviewanskquestions Avatar asked Jun 20 '11 12:06

codereviewanskquestions


People also ask

How do you make a function thread-safe?

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.

Is C write thread-safe?

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.

Is printf thread-safe in C?

the standard C printf() and scanf() functions use stdio so they are thread-safe.

Are static variables thread-safe in C?

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.


2 Answers

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.

like image 120
Richard Pennington Avatar answered Oct 22 '22 07:10

Richard Pennington


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.

like image 31
Vinicius Kamakura Avatar answered Oct 22 '22 08:10

Vinicius Kamakura