1

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?

Nikita
  • 6,270
  • 2
  • 24
  • 37

2 Answers2

2

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); });
} 
Nikita
  • 6,270
  • 2
  • 24
  • 37
  • Thx its working! How can i make it infinite? I need recieve packet from asynchronous server and if i run it it says terminate called without an active exception and if i join it or detach it - program will crash. –  Sep 03 '16 at 19:13
  • @lika85456 If I understand you correct, you can use infinite loop inside `func_to_be_thread`. But seems it's better to create the other question and put the problematic code there. It will give a chance to better analyse the new problem and give a better advice. – Nikita Sep 03 '16 at 19:54
  • i cant create another question becouse i need to wait 2 days ._. And thx i check that mark :) –  Sep 03 '16 at 20:13
0

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

Community
  • 1
  • 1
HazemGomaa
  • 1,620
  • 2
  • 14
  • 21