Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

ref use

29 views
Skip to first unread message

Popping mad

unread,
Nov 16, 2016, 5:38:19 AM11/16/16
to le...@nylxs.com
I'm reading up on concurrency with the thread libraryis C++ Concurrency
in action by Anthony Williams and I'm puzzled by one example having to do
with sending references of objects through the threads. If you own the
text, it is one page 24 where he is callable functions is

void update_data_for_widget(widget_id w, widget_data& data);

the call for the thread is

std::thread t (update_data_for_widget, w, data); where data is an object,
of data I suppose ;)

to do this correctly he says we need to use ref and a reference wrapper

std::thread t(update_data_for_widget, w, std::ref(data) );

Why can't you just send a reference?

std::thread t(update_data_for_widget, w, &data );

ruben safir

unread,
Nov 18, 2016, 9:13:11 PM11/18/16
to
nadah on this?

Alf P. Steinbach

unread,
Nov 19, 2016, 7:01:27 AM11/19/16
to
Because these arguments are not passed on directly to the thread
function: they're stored by value, and passed on later.


> std::thread t(update_data_for_widget, w, &data );

This is not a reference, it's a pointer.

A pointer would work fine, it can be stored by value, but then the
thread function signature needs to be adjusted accordingly.


Cheers & hth.,

- Alf



Manfred

unread,
Nov 19, 2016, 11:00:12 AM11/19/16
to
On 11/19/2016 12:58 PM, Alf P. Steinbach wrote:
>> std::thread t(update_data_for_widget, w, std::ref(data) );
>>
>> Why can't you just send a reference?
>
> Because these arguments are not passed on directly to the thread
> function: they're stored by value, and passed on later.

Reminds me of a similar question I had:
http://thread.gmane.org/gmane.comp.gcc.help/49709

see also:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68784

I was also surprised; in principle the language semantics could allow
using a reference type, but this is intentionally disabled by the
standard for std::thread - you have to explicitly use std::ref().
Apparently this was motivated by 'helping' the programmer not pass data
by reference accidentally between threads.
I am not sure I like this approach, though. I think that it is a basic
knowledge of any skilled C++ programmer to know how to use references.

What I like of C++ is its solid foundation of self-consistent language
logic. Introducing this type of exception to the basic semantics is not
really attractive to me.
0 new messages