Subject: Re: [boost] [thread] thread_specific_ptr, dangerous conflation of identity and address
From: Edd Dawson (lists_at_[hidden])
Date: 2010-02-16 18:09:44
On 2/16/2010 8:44 AM, Anthony Williams wrote:
> I think that using a thread_specific_ptr as an automatic variable is
> incorrect usage. The lifetime of the variable is strictly limited to the
> duration of the function call, and each thread that calls the function
> will get its own copy of the thread_specific_ptr. Under such
> circumstances you really ought to just use a plain ordinary variable.
If this is the case then the documentation really ought to say this to set a
precedent, I think.
However, is it not so far fetched to imagine somebody calling a "big" function
of library A, which has a thread_specific_ptr in auto storage and then
afterwards calling a "big" function in a completely unrelated library B, which
also allocates an auto thread_specific_ptr?
I personally hit the problem when running a parallel algorithm where each thread
needed to modify a data structure. I created a wrapper around
thread_specific_ptr that allowed each thread to have its own copy of a
"prototype" data structure to work on:
ThreadLocal<vector<Data> > tlData(defaultVector);
ParallelForEach(threadPool, input.begin(), input.end(),
bind(&ModifyArbitraryElements, _1, Ref(tlData));
// Ref() is like boost::ref() but models a reference to
// thread-local data.
After all threads were finished, a quick serial pass then merged the data for
the different threads together:
BOOST_FOREACH(const std::vector<Data> &dataVec, tlData)
Of course, running this parallel algorithm multiple times is what caused
problems. Since the thread-local data was only needed for the duration of the
algorithm, the use of automatic storage seemed rather sensible. But of course I
/would/ say that :)
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk