Thread safety - again...

Phil Edwards phil@jaj.com
Sun Feb 24 20:56:00 GMT 2002


On Sat, Feb 23, 2002 at 06:27:27PM +0100, Stefan Olsson wrote:
> 
> string shared::find_in_shared_map( string key )
> {
>         string tmp = "";
> 
>         if( shared_map.find( key ) != shared_map.end() )
>         {
>                 tmp = shared_map[ key ];
>         }
> 
>         return tmp;
> }

If you /really/ want to make certain that this won't change the object,
mark it as a const member function, and pass the string by reference-to-
const for efficiency:

    class shared
    {
        ....
        string find_in_shared_map( string const& key ) const ;
                                          ^^^^^^       ^^^^^
    };

(You may already have this stuff; I'm mainly writing it for the audience.)

Doing this, you'll find that map's operator[] cannot be used for non-const
objects.  That should lead you to use the return value from find()
rather than making, essentially, a second call to find() inside op[].
Something like

    string shared::find_in_shared_map (string const& key) const
    {
        string tmp;
        map<.....>::iterator i = shared_map.find(key);

        if (i != shared_map.end())
            tmp = i->second;

        return tmp;
    }

(unchecked, off-the-top-of-my-head code)


> In this case there is no method that alters the map container, in which 
> case a mutex would have been needed, but is the above according to the 
> rules or not?

I /think/ so, but I'm not the threading expert.


Phil

-- 
If ye love wealth greater than liberty, the tranquility of servitude greater
than the animating contest for freedom, go home and leave us in peace.  We seek
not your counsel, nor your arms.  Crouch down and lick the hand that feeds you;
and may posterity forget that ye were our countrymen.            - Samuel Adams



More information about the Libstdc++ mailing list