views:

217

answers:

5

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

+11  A: 

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

Shirik
You mean a variable not part of the function being called right, like if AddTwo modified a global variable?
Milo
Correct. I'm talking about the address 'num' references, not 'num' itself. Your example of trying to modify a global variable from multiple threads is one of the problem cases.
Shirik
Okay, well my application will be dividing work up so this shouldn't be a problem, thanks!
Milo
+1  A: 

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.

ckv
+1  A: 

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

taemu
A: 

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.

John Burton
A: 

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.

Makis