开发者

In a multithreaded app, can 2+ threads access the same function if the function does not modify/read data or modifies/reads temporary data?

I can't seem to find an answer anywhere on Google. I basically want to know if 2 threads can access normal/member functions like these at the same time and not result in开发者_StackOverflow undefined behavior or do I have to use a mutex?

void foo(void)
{
  float x(133.7);
  float y(10);
  std::cout << std::endl << (x * y);
}

void foobar(void)
{
  std::cout << std::endl << 1/1;
}


I am pretty sure your code doesn't have undefined behaviour.

That said, you are using shared data, namely std::cout.

So if you expect std::cout << std::endl << (x * y) to be executed as a single operation (e.g. to prevent bits of output from different threads getting interleaved on stdout), you are going to have to use locks.


I basically want to know if 2 threads can access normal/member functions like these at the same time and not result in undefined behavior or do I have to use a mutex?

Yes. You only need the synchronization if the threads will be using shared data. Synchronization is more about protecting the state, not the code itself.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜