Home > Backend Development > C++ > How Can I Safely Pass Object References to C 11 Threads?

How Can I Safely Pass Object References to C 11 Threads?

Patricia Arquette
Release: 2024-11-19 14:57:03
Original
590 people have browsed it

How Can I Safely Pass Object References to C  11 Threads?

Passing Object Reference Arguments to Thread Functions: A Constructor Issue

In C 11, the std::thread interface allows for the creation of lightweight threads. One common task is passing arguments to these thread functions, but difficulties may arise when attempting to pass object references.

Consider the following example:

void foo(int &i) { std::cout << i << std::endl; }
int k = 10;
std::thread t(foo, k);
Copy after login

This code successfully compiles and runs, as integers are copied into the thread function. However, passing an std::ostream object reference doesn't compile:

void foo(std::ostream &os) { os << "This should be printed to os" << std::endl; }
std::thread t(foo, std::cout);
Copy after login

The error indicates a missing or inaccessible constructor.

Solution: Using std::ref

Threads copy their arguments by default. To pass a reference explicitly, an alternative approach is needed. This is where std::ref comes in. It wraps an object reference in a value-semantics wrapper.

By using std::ref, the thread function receives a copy of the wrapper, but the wrapped reference remains the same:

std::thread t(foo, std::ref(std::cout));
Copy after login

This enables the thread function to access and modify the original object, allowing for the desired functionality.

It's crucial to note that the object being referenced must remain accessible throughout the thread's execution. If it's deleted or modified before the thread finishes, unexpected behavior or crashes might occur.

The above is the detailed content of How Can I Safely Pass Object References to C 11 Threads?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template