Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ threads – Are threaded-function's function calls part of the thread?

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading