Say I have my code defined this way
class One
{
//...
//method2();
//method3(); ...
void method1() { method2(); method3(); }
};
int main()
{
One obj;
std::thread tmethod1(One::method1, obj);
//...
tmethod1.detach();
}
Will executing obj.method1() also put the calls to methods 2 and 3 on that separate thread?
(I will not call method2 or method3 by themselves ever in the code).
I do not intend to join the thread with main, I wish to keep it detached. Therefore, even if main ends, I want the separate thread and all calls in methods 2 or 3 to still run.
Thanks!
>Solution :
Yes, the calls to method2() and method3 are executed in the same thread in which method1() was called; namely, the thread that was started on line 2 of main.
Once a thread is started, everything done by the thread’s function occurs in that thread, except of course for operations that are specifically defined to start more new threads, or to trigger execution of code in another thread (e.g. standard library functions with an appropriate execution policy). Otherwise, code doesn’t spontaneously "jump" between threads.