#include <iostream>
#include <thread>
template<int Num>
class MyClass {
public:
MyClass(int val) : val_(val) {}
private:
int val_;
};
template<int Num>
void threadFunction(MyClass<Num> myObj) {
std::cout << "Inside thread" << std::endl;
}
int main() {
MyClass<1> obj(42);
std::thread t1(threadFunction<1>, obj); // <-- pass by value
std::thread t2(threadFunction<1>, std::ref(obj)); // <-- pass by reference
t1.join();
t2.join();
return 0;
}
I want to pass an object by value to a thread to ensure each thread works on its own copy (thread t1).
When I create thread t2, I pass the object by reference using std::ref(obj).
Clearly, my intention per function definition is to pass the object by value rather than by reference. Is obj a shared variable if passed as std::ref(obj) among all threads?
This question
std::ref using with template function and function passing by value
seems to address a similar topic, but not in multithreading context. In the example shown there, there seems to be a difference if the function is templated.
Mathieu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2