Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe for multiple threads to call the same function?

Is it safe to for example do:

void AddTwo(int &num)
{
  num +=2;
}


void ThreadProc(lpvoid arg)
{
AddTwo((int)arg);

}

Would it be safe for this to occur if 4 threads were doing this at the same time? Thanks

like image 325
jmasterx Avatar asked Jul 05 '10 05:07

jmasterx


People also ask

What will happen if multiple threads accessing the same resource?

Multiple threads accessing shared data simultaneously may lead to a timing dependent error known as data race condition. Data races may be hidden in the code without interfering or harming the program execution until the moment when threads are scheduled in a scenario (the condition) that break the program execution.

Can two threads access same method?

If another thread enters the method, it will have its own num (because it called its own version of the method) but it will be using the same outside number because that number is global and accessable to all. In this case you will need to add special code to make sure your threads behave correctly.

Can multiple threads access the same variable?

Only one thread can read and write a shared variable at a time. When one thread is accessing a shared variable, other threads should wait until the first thread is done. This guarantees that the access to a shared variable is Atomic, and multiple threads do not interfere.


5 Answers

The function itself is safe to call. It becomes dangerous if they're all trying to operate on the same variable.

like image 109
Shirik Avatar answered Oct 18 '22 20:10

Shirik


As a general rule of thumb, a function is re-entrant if it doesn't alter any common resources (e.g. same memory locations). If it does, you need to use some sort of synchronization mechanism like mutexes or semaphores.

like image 41
Makis Avatar answered Oct 18 '22 22:10

Makis


There is nothing wrong in calling same function from different threads. If you want to ensure that your variables are consistent it is advisable to provide thread synchronization mechanisms to prevent crashes, racearound conditions.

like image 21
ckv Avatar answered Oct 18 '22 21:10

ckv


The safey depends on the value of lpvoid arg.

If All of the args are different each other, then safe otherwise not.

To make function call safe, Check out 'mutex'.

like image 43
taemu Avatar answered Oct 18 '22 22:10

taemu


The real answer is - it depends...

On most platforms, yes it's safe as long as you don't do anything unsafe in the function which others have mentioned. It's easy to mess up so be careful!

On other platforms it's most definately unsafe. For example most C compilers for the smaller PIC microcontrollers can't support this due to hardware limitations.

In general, yes it's safe though.

like image 44
jcoder Avatar answered Oct 18 '22 20:10

jcoder