Passing Object References to Thread Functions: Understanding the Challenges
In C 's std::thread interface, passing object reference arguments to thread functions can encounter compilation errors. This article explores the underlying reasons for these errors and provides solutions.
Understanding Object Reference Passing
In the provided example, an integer (k) can be passed to a thread function as follows:
void foo(int &i) { // Do something with i std::cout << i << std::endl; } int k = 10; std::thread t(foo, k);
However, attempting to pass an ostream reference to a thread function results in a compilation error:
void foo(std::ostream &os) { // Do something with os os << "This should be printed to os" << std::endl; } std::thread t(foo, std::cout);
The Deleted Constructor
The compilation error is rooted in the fact that std::thread has a deleted constructor that prevents direct object reference passing. This is intentional, as threads should copy their arguments to avoid race conditions.
The Solution: std::ref
To pass an object reference explicitly, wrap it with std::ref (or std::cref for constant references). This solution ensures that a copy of the reference is passed to the thread function, ensuring safety:
std::thread t(foo, std::ref(std::cout));
Preserving Object Lifetime
It is crucial to note that the reference wrapper only contains a reference to the object. Hence, it is essential to ensure that the object remains alive throughout the thread's execution. Failure to do so will result in undefined behavior.
The above is the detailed content of Why Does Passing Object References to C Threads Cause Compilation Errors?. For more information, please follow other related articles on the PHP Chinese website!