Hello, recently I had to start developing a multi-threaded application (for the first time) and came across such a problem: I need to create a thread for a specific object with the transfer of a non-static function to the designer, Google did not give anything worthwhile.

  1. Tell me, is it even possible?
  2. If not, how is it treated?

In the abstraction: there is a System class, it has a non-static private update() method that I have to monitor by initializing the private thread* Thread pointer in the class constructor.

PS the update method calls the move(...) , which is tied to the object, that is, I cannot make the update static without creating a container that stores all user data, and this is expensive

 #include <thread> //еще включения ... class System { //некоторые поля и методы... //... thread* Thread; static thread* sThread; System() { Thread = new thread(update);//ошибка! отсутствуют экземпляры констуктора соответствующий ... для std::thread::thread (void()) } void update() { //... move(...); //... } void move() { //работает с полями объекта } }; { //где-то создается System* system = System; } 

PS (2) Climbed with c #, there you can initialize threads with non-static methods (sort of), do not judge strictly

  • And lambda not help? - Qwertiy
  • @Qwertiy, uh, how can lamba expressions come in here? I can't replace this method with the lambboy, the thread constructor accepts a link to the address of the function, and I need it exactly as I wrote (rewrite the program with C # - Xambey
  • As I understand it, you want to create a stream whose function depends on the state of the object? Those. to let a thread execute a member function of a class? - Shadasviar
  • @Shadasviar exactly! - Xambey
  • @Xambey, and the creation of a thread is carried out inside a member function of a class or outside it? - Shadasviar

4 answers 4

The documentation states that the constructor looks like this:

 template< class Function, class... Args > explicit thread( Function&& f, Args&&... args ); 

so I can assume that you should use the lambda function something like this:

 new thread([&]() { this.update(); }) 

In any case, be careful with the lifetime of objects.

    Also possible with std::bind

     System() { Thread = new std::thread(std::bind(&System::update, this)); } 
    • new std::thread(std::bind, System::update, this); ?))) - Qwertiy
    • Thank you, sorry you can’t choose a few answers - Xambey
    • @Qwertiy no, it will be a call to bind instead of a call to update - Pavel Mayorov

    I'm absolutely not sure that this is a good idea, but using lambda instead of update and additionally giving the compiler the -pthread option I was able to run, and even get the result of the following code:

     class System { //некоторые поля и методы... //... static thread* sThread; public: thread* Thread; System() { Thread = new thread([this]{ /*Это код метода update, который вызывает move, лямбда должна захватить указатель на текущий объект чтоб вызвать функцию объекта */ cout << "Updte\n"; this->move(); }); } private: void move() { cout << "Move\n"; } }; int main(){ System s; s.Thread->join(); return 0; } 

    I repeat that, in my opinion, this all has a lot of pitfalls, so it is interesting to see the answers of more knowledgeable people.

      And why is it difficult if you can just? Specify a member function and add this ?

       #include <thread> #include <iostream> using namespace std; class Test { public: Test(int x):x(x){}; void out(int b) { cout << x << ":" << b << endl; } void run(int j) { thread t = thread(&Test::out,this,j); t.join(); } private: int x; }; int main() { Test t(12); t.run(3); }