简体   繁体   中英

How to use a thread member variable of a class c++

I'd like to have a thread variable as a class member like this:

class Example{
    public:
        void startTask();
    private:
        std::thread m_taskThread;
}

my questions are:

  1. Assuming that the creation of this thread object will happen in startTask() , what is the scope of this thread object? Does it live till the Example class object gets destroyed like normal member variables? Or its scope is the scope of that particular method( startTask() )?

  2. Where should I call .join() on the spawned thread if I want this thread to live as long as the Example object? In the destructor of Example class?

  3. Some material( https://thispointer.com/c11-how-to-use-stdthread-as-a-member-variable-in-class/ ) online says I should create move-only class if I need to use std::thread as member variable, why is that?

  4. Is it good to have a thread object as a member variable? Reasons?

Assuming that the creation of this thread object will happen in startTask(), what is the scope of this thread object? Does it live till the Example class object gets destroyed like normal member variables? Or its scope is the scope of that particular method(startTask())?

The scope of the thread object is at the level of the Example object. But, the thread will not start running until you call startTask(). Do no confuse having a thread instance and having a running thread instance.

Where should I call .join() on the spawned thread if I want this thread to live as long as the Example object? In the destructor of Example class?

Yes, you can call it at the destructor and it is safe.

Some material( https://thispointer.com/c11-how-to-use-stdthread-as-a-member-variable-in-class/ ) online says I should create move-only class if I need to use std::thread as member variable, why is that?

Because the std::thread is not copyable, but it is movable. So your example class cannot be copyable as well.

Is it good to have a thread object as a member variable? Reasons?

Yes, why not. I see no problem with that. You create one class with the responsibility of managing a resource, that is a thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM