user6200749
user6200749

Reputation:

Make thread in class and use it in class C++

i need make new thread in class and use it. Somethink like:

class Somethink
{
  public: 
    func_to_be_thread();
    init_func();
}

Somethink::init_func()
{
  std::thread newThread(func_to_be_thread);
}

int main()
{
  Somethink ss;
  ss.init_func();
}

EDIT: How to make it correctly? Everythink i wrote returns error becouse idk how to make new thread in class with parameter (function to run) class method. My question is how to do it correctly?

Upvotes: 1

Views: 188

Answers (2)

Nikita
Nikita

Reputation: 6427

If you need to create a thread with member function you can do the following:

class Something
{
   public: 
     void func_to_be_thread();
     void func_to_be_thread_advanced(const char* arg1);

     std::thread init_func();
     std::thread init_func_with_param(const char *arg1);
}

std::thread Something::init_func()
{
  return std::thread(&Something::func_to_be_thread, this);
}

Also you can do it with lambda and parameters:

std::thread init_func_with_param(const char *arg1)
{
  return std::thread([=] { func_to_be_thread_advanced(arg1); });
} 

Upvotes: 2

HazemGomaa
HazemGomaa

Reputation: 1630

which C++ version are you using ? you can use std::thread only starting C++11 .. if you need more help with the syntax, you can check std::thread calling method of class Start thread with member function

Upvotes: 0

Related Questions