Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start thread with function object with argument

I code snipped below:

#include <iostream>
#include <thread>


class Me{
public:
bool isLearning;
 void operator()(bool startLearning){
  isLearning = startLearning;
 }
};

int main(){
Me m;
std::thread t1(m(true));
t1.join();
std::cout << m.isLearning << std::endl;
}

I can't start thread with callable object when argument is passed, is there any way to start thread and pass callable object with argument in thread constructor?

like image 379
Mateusz Wojtczak Avatar asked Jan 27 '26 07:01

Mateusz Wojtczak


1 Answers

Problem #1

std::thread t1(m(true)); does not do what you think it does.

In this case you are invoking your function object and passing it's result (which is void) to the constructor of std::thread.

Solution

Try passing your function object and arguments like this:

std::thread(m, true);

Problem #2

std::thread will take a copy of your function object so the one it uses and modifies will not be the same one declared in main.

Solution

Try passing a reference to m instead by using std::ref.

std::thread(std::ref(m), true);

like image 132
Mohamad Elghawi Avatar answered Jan 28 '26 20:01

Mohamad Elghawi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!