25

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

1
  • I just did this as an example, I know this isn't 'correct'
    – jmasterx
    Jul 5, 2010 at 5:09

5 Answers 5

27

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

3
  • You mean a variable not part of the function being called right, like if AddTwo modified a global variable?
    – jmasterx
    Jul 5, 2010 at 5:09
  • 3
    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
    Jul 5, 2010 at 5:10
  • Okay, well my application will be dividing work up so this shouldn't be a problem, thanks!
    – jmasterx
    Jul 5, 2010 at 5:13
4

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.

2

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.

1

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

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.