0

I am trying to understand the multithreading in c++. I am trying to call a function in another class using two threads as shown below:

vmgr.h

class VMGR{

public:
    int helloFunction(int x);
    
};

vmgr.cpp

#include"vmgr.h"
#include<iostream>

int VMGR::helloFunction(int x){

    std::cout<< "Hello World="<< x << std::endl;

    return 0;

}

main.cpp

#include <stdlib.h>
#include <iostream>
#include<iostream>
#include<thread>
#include<chrono>
#include<algorithm>
#include "vmgr.h"

using namespace std::chrono;


int main(int argc, char* argv[]) {

    VMGR *vm= new VMGR();

    std::thread t1(vm->helloFunction,20);
    std::thread t2(vm->helloFunction,30);

    t1.join();
    t2.join();


   return 0;
}

The error I am getting is Invalid use of non-static member function int VMGR:: helloFunction(int) Not sure how to resolve this error. Thank you in advance.

Manu
  • 69
  • 8
  • You need to either use a lambda function (which captures `vm`) or pass a proper pointer to member function (e.g.: `&VMGR::helloFunction`) and `vm` as first argument to the `thread` constructor – UnholySheep Jul 16 '22 at 19:55
  • This doesn't address the question, but there's no reason in this code to create the `VMGR` object on the free store. `VMGR vm;` will work just fine, with less overhead. And without the memory leak that the current code has (it doesn't `delete vm;`). – Pete Becker Jul 16 '22 at 19:59
  • Thank you @PeteBecker. I will make these changes suggested by you in the code. – Manu Jul 16 '22 at 20:08

1 Answers1

1

The constructor of std::thread uses std::invoke passing copies of the constructor parameters.

std::invoke can, among other alternatives, be called with member function pointers. This requires syntax different to the one used in the question:

std::thread t1(
    &VMGR::helloFunction, // member function pointer
    vm,                   // pointer to the object to call the function for
    20                    // function parameter
);

std::thread t2(&VMGR::helloFunction, vm,30);
fabian
  • 80,457
  • 12
  • 86
  • 114
  • Hi @fabian, if the function which is called by thread returns a value, then what should be syntax? – Manu Jul 16 '22 at 20:30
  • @Deepika You're probably looking for something like [`auto f = std::async(std::launch::async, &VMGR::helloFunction, vm,30);`](https://en.cppreference.com/w/cpp/thread/async) returning a `std::future` that can be used await completion of the function & retrieve the value. There are of course other ways of communicating back results from a thread, this is just the most convenient one. – fabian Jul 16 '22 at 20:35