Home > Blockchain >  How to pass the target function of std::thread constructor as an argument
How to pass the target function of std::thread constructor as an argument

Time:11-19

I can do this to start my thread:

int main_test() {
  // do something...
  return 0;
}

std::thread* myThread;

void myFunction() {
  myThread = new std::thread(main_test);
}

How do I pass main_test as an argument to myFunction, so the same function can be used to start the thread using different target functions? What would the signature of myFunction be then?

I guess what I don't understand is how the templated version of the std::thread constructor is invoked with a specified type.

CodePudding user response:

std::thread myThread;

The type of myThread is std::thread.

myThread = new std::thread(main_test);

new std::thread(main_test) returns std::thread*. You cannot assign std::thread* into a std::thread. The program is ill-formed.

Solution: There appears to be no reason to use dynamic allocation. Simply assign a temporary object like this:

myThread = std::thread(main_test);

How do I pass main_test as an argument to myFunction, so the same function can be used to start the thread using different target functions? What would the identity of myFunction be then?

You can make your myFunction a template with exactly the same arguments as std::thread has, and forward everything. Or, if you want to keep it simple, you can use a function pointer.

CodePudding user response:

How do I pass main_test as an argument to myFunction, so the same function can be used to start the thread using different target functions?

You can pass the poiter to your function as an argument

void myFunction(int (*func)()) {
myThread = new std::thread(func);
}

int callSelector(int someCriteria)
{
    if (someCriteria == 0) {
        myFunction(main_test1);
    }
    else {
        myFunction(main_test2);
    }
}
  • Related