Thread safety - again...

Stefan Olsson stefan@noname4us.com
Sat Feb 23 11:59:00 GMT 2002


The topic is on the list every now and then, and I guess that most of us 
has read the SGI definition several times which states that:

"The SGI implementation of STL is thread-safe only in the sense that 
simultaneous accesses to distinct containers are safe, and simultaneous 
read accesses to to shared containers are safe. If multiple threads 
access a single container, and at least one thread may potentially 
write, then the user is responsible for ensuring mutual exclusion 
between the threads during the container accesses."

However I still feel a bit uncertain about the meaning of this when 
talking about container methods (i.e. find()).

Consider the following example (Errorchecking and formatting not perfect 
;-):

#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <map>

using namespace std;

/*
 * Define a class that will be shared among several threads
 */
class shared
{
        map< string, string > shared_map;

        public:
                shared();
                ~shared();

                string find_in_shared_map( string key );
};

shared::shared()
{
        /*
         * Insert some test data
         */
        shared_map[ "a" ] = "a";
        shared_map[ "b" ] = "b";
        shared_map[ "c" ] = "c";
}

shared::~shared()
{
}

string shared::find_in_shared_map( string key )
{
        string tmp = "";

        if( shared_map.find( key ) != shared_map.end() )
        {
                tmp = shared_map[ key ];
        }

        return tmp;
}

/*
 * Workers that will make calls to the shared class instance
 */
void* worker( void* arg )
{
        shared *local_shared = (shared*)arg;

        string retval;

        while( true )
        {
                retval = local_shared->find_in_shared_map( "a" );
        }
}

int main()
{
        shared *main_shared = new shared();

        pthread_t *thread;
        pthread_attr_t pthread_attr_default;
        pthread_attr_init(&pthread_attr_default);

        for( int i=0; i < 4; i++ )
        {
                thread = new pthread_t;
                pthread_create( thread, &pthread_attr_default, worker, 
main_shared );
        }

        sleep( 10 );

        return 0;
}

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?

Thanks!

/Stefan

-- 
Confidence is the feeling you have before you understand the
situation.




More information about the Libstdc++ mailing list