How to invoke member function safely when inheriting std::thread

std::thread member function
c thread member function with arguments
thread' is not a member of 'std
c++ thread::join
multithreading in c++ pdf
multithreading in c++ windows
c++ thread::detach
c thread pointer

My code is as below:

  class MyThread : public std::thread {
        int a_;

    public:
        MyThread(int a)
            : std::thread(&MyThread::run, this),
              a_(a)
        { }

        void run() {
            // use a_
        }
    };

I want to have my own thread class which has all the methods that std::thread provides, so I let MyThread class inherit std::thread. In MyThread's constructor, I pass its member function to std::thread. The compilation is OK, but I am concerned it there a race condition between invoking run() in std::thread's construtor and initializing a_.

Is there a way to make it safe?

Don't do it that way. "Has-a" (composition) has a lot of advantages over "is-a" (inheritance).

class MyThread
{
    std::thread _thread;
    int _a;
public:

    MyThread(int a) : _a(a)
    {
        _thread = std::thread([this] {run();});
    }

    void run()
    {
       // thread code here
    };

    void join()
    {
        _thread.join();
    }
};

A better approach would be to recognize that the thread and the operation on that thread are two distinct objects:

class WorkerOperation
{
    int _a;
public:
   WorkerOperation(int a) :  _a(a)
   {
   }

   void run()
   {
     // your code goes here
   }
};

And then to create a thread:

shared_ptr<WorkerOperation> spOp = make_shared<WorkerOperation>(42);
std::thread t = std::thread([spOp] {spOp->run();});

And if you really need to pair up the operation and the thread:

std::pair<WorkerOperation, std::thread> threadpair;
threadpair.first = spOp;
threadpair.second = std::move(t);

C++11 : Start thread by member function with arguments , When std::thread will internally create a new thread, it will use this passed member function as thread function. But to call a member function,  When std::thread will internally create a new thread, it will use this passed member function as thread function. But to call a member function, we need a object. 2.) Pointer to the object of class Task As a second argument we passed a pointer to the object of class Task, with which above member function will be called. In every non static member function, first argument is always the pointer to the object of its own class.

To fix the error you can write:

    MyThread(int a)
        :a_(a)
    { 
        (std::thread&)(*this) = std::thread(&MyThread::run, this);
     }

This way, the thread is run with initialized a_.

In general, I don't think it is a good idea to inherit from std::thread. Better make it a private member and run it. Otherwise user can do weird shit if you allow them to cast your class to std::thread& publicly. Like executing a different function than what you intended.

C++ Multithreading - Threading in C++, Thread joining is done by using join() member function of a thread class: Not joinable thread can be destroyed safely. std::mutex m;//door handle void makeACall() { m.lock();//person enters the call box and locks the door //now it can talk to  When a member function is called with a derived class object, the compiler first looks to see if that member exists in the derived class. If not, it begins walking up the inheritance chain and checking whether the member has been defined in any of the parent classes.

but I am concerned it there a race condition between invoking run() in std::thread's construtor and initializing a_.

Yes,

You might reorder member/base:

struct MyThreadData
{
    int _a;
};

struct MyThread : MyThreadData, std::thread
{
public:
   explicit MyThread(int a) : MyThreadData{a}, _thread([this] {run();}) {}

    void run()
    {
       // thread code here
    };
};

sf::Thread Class Reference (SFML / Learn / 2.5.1 Documentation), Inheritance diagram for sf::Thread: Construct the thread from a member function and an object. boost/std::bind); functors with one argument of any type; member functions from any class with no argument sf::Thread thread(&Task::​run, &task); Terminating a thread with this function is not safe, and can lead to local  You can use Type.InvokeMember to set a field to a particular value by specifying BindingFlags.SetField. For example, if you want to set a public instance field named F on class C, and F is a String, you can use code such as: typeof(C).InvokeMember("F", BindingFlags.SetField, null, c, new Object[] {"strings new value"}, null, null, null);

std::thread, std::swap(std::thread). (C++11). specializes the std::swap algorithm (function) [​edit]. Retrieved from  Member function, gives id of associated thread object i.e. std::thread::get_id() To get the identifier for the current thread use, std::this_thread::get_id() If std::thread object does not have an associated thread then get_id() will return a default constructed std::thread::id object i.e. not any thread.

C++11: std::threads managed by a designated class, Okay, but the default std::thread constructor is pretty pointless here, be to have the constructor notify the thread when it is safe to start, from within its body. This means the starting thread would start from calling a wrong function, Most of G's search results for “c++ thread as class member” discuss how  Thread destructor (public member function ) operator= Move-assign thread (public member function ) get_id Get thread id (public member function ) joinable Check if joinable (public member function ) join Join thread (public member function ) detach Detach thread (public member function ) swap Swap threads (public member function ) native_handle

The C++ Thread Classes, The Ice run time installs an exception handler that calls ::std::terminate if run This member function starts a newly-created thread (that is, calls the run method). Each class implements the pure virtual run method it inherits from its base class. the numbers from 1 to 100 into an instance of the thread-safe Queue class we  Initialization of function-local statics is guaranteed to occur only once even when called from multiple threads, and may be more efficient than the equivalent code using std::call_once. The POSIX equivalent of this function is pthread_once .

Comments
  • which has all the methods that std::thread provides Which methods are you referring to exactly? You do not need to inherit to access the public member functions. Accessing protected member functions and variables could be a case but I don't know of any.
  • @TrickorTreat, methods like join() or get_id(). I don't want to add these interfaces again in MyThread by composing and adapting a std::thread object, so I subclass std::thread directly.
  • Well, this might be a workaround after adding an override of MyThread& operator=(std::thread&&). Thanks @alx23z