Boost logo

Boost :

From: William E. Kempf (wekempf_at_[hidden])
Date: 2003-07-01 09:00:46


Philippe A. Bouchard said:
> William E. Kempf wrote:
>
>>
>> Philippe A. Bouchard said:
>>> William E. Kempf wrote:
>>>
>>> [...]
>>>
>>>> As already pointed out, to associate data with a thread you use
>>>> thread_specific_ptr. BTW, you still have to remember that the
>>>> functor is copied, and data passed to/in the functor is not
>>>> considered part of the thread in any event.
>>>
>>> Ok, how do you find out the data of the current thread? The key in
>>> boost::detail::tss is not the same as the one in boost::thread.
>>
>> What data? The actual thread data (there's not much, beyond the
>> thread id which isn't direclty accessible) is found by calling the
>> default c-tor on the thread. The data passed in the functor is your
>> responsibility. Either you explicitly pass it everywhere that's
>> needed, or the thread stores it in a tss key.
>>
>
> Suppose you have:
>
> struct functor1
> {
> list<void *> m_list;
>
> void operator () ()
> {
> ...
> }
> };
>
> struct functor2
> {
> list<void *> m_list;
>
> void operator () ()
> {
> ...
> }
> };
>
> int main()
> {
> thread f1(functor1());
> thread f2(functor2());
>
> ...
>
> // I would like to access m_list of the current thread's
> functor:
>
> lock()...
> if (thread() == f1 || thread() == f2)
> {
> thread()..(whatever casts)...m_list;
> }
> unlock()...
>
> // I think the only way to do this is by mapping the thread's id
> // with the object's address (map<key, functor1 *>) but there
> is // no standard key publicly accessible and map<> creates
> overhead.
> }

The functor may be copied any number of times, so this is problematic. If
you passed it by reference, possibly using boost::ref, then the answer
would be to just retain the functor as a named variable instead of passing
a temporary. I'd say that's typically the answer for most use cases. For
some, you may want to place the functor in a thread_specific_ptr<>, as
suggested, but this only allows you to recover the data for the current
thread.

The only way I can see to give the interface your suggesting is to either
type the thread, which is problematic for so many reasons, or to employ
something similar to boost::any.

-- 
William E. Kempf

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk