Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I call an objects member function from a different thread?

If I have an C++ object created in the main thread, and then start another thread, and from that thread I call a public member function of the object I created, what happens?

Is it different if the public function has parameters or if it manipulates private object members?

Does it behave differently on windows, linux or mac os?

What happens if the object is created on the stack?

like image 636
GlassFish Avatar asked Mar 14 '12 07:03

GlassFish


2 Answers

There are two points that matter:

  • first, as usual, you need to esnure that the lifetime of the instance exceeds the duration of its usage.
  • second, access to variables across multiples threads need be synchronized to prevent race conditions.

That's all folks.

like image 151
Matthieu M. Avatar answered Sep 26 '22 02:09

Matthieu M.


  1. Each thread has a own stack and thus you can have concurrent streams of execution. It is your own duty to make the object thread-safe.

  2. It does not matter. However, private members are a candidate for race conditions.

  3. If you create an object on the stack, it won't be accessible from another thread.

like image 35
Matthias Avatar answered Sep 27 '22 02:09

Matthias