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
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.
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.
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.
The function itself is safe to call. It becomes dangerous if they're all trying to operate on the same variable.
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.
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.
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'.
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.
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