开发者

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

开发者 https://www.devze.com 2023-01-05 22:07 出处:网络
Is it safe to for example do: void AddTwo(int &num) { num +=2; } vo开发者_如何学运维id ThreadProc(lpvoid arg)

Is it safe to for example do:

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


vo开发者_如何学运维id 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号