This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Thread safety - again...
- From: Stefan Olsson <stefan at noname4us dot com>
- To: libstdc++ at gcc dot gnu dot org
- Date: Sat, 23 Feb 2002 18:27:27 +0100
- Subject: Thread safety - again...
- Organization: Noname4us
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.