Thread safety clarification
Loren James Rittle
rittle@latour.rsch.comm.mot.com
Thu Nov 1 13:59:00 GMT 2001
>> Are there examples of objects which cannot be accessed from multiple
>> threads simultaneously?
> Assuming you are speaking about one instantiated object being known to
> multiple threads, this is the default assumption you must make as an
> application writer using g++ 3.0 and its implementation of the
> standard library.
[Sorry to followup myself...]
OK, here as a real example that *might* have worked to some definition
with libstdc++-v2 on some platforms that is explicitly *not
guaranteed* to work to any definition with libstdc++-v3. You might be
surprised by this one...
// On POSIX platforms only (configured or defaulted to --enable-thread=posix),
// compile with some variation of ``g++ -pthread''
#include <pthread.h>
#include <string>
#include <iostream>
const std::string a = "A really long read-only string...";
const std::string b = "B really long read-only string...";
void*
thread_a_code (void* t)
{
while (true)
std::cout << a << std::endl;
}
void*
thread_b_code (void* t)
{
while (true)
std::cout << b << std::endl;
}
int
main (int argc, char** argv)
{
pthread_t thread_a;
pthread_t thread_b;
pthread_create (&thread_a, NULL, thread_a_code, NULL);
pthread_create (&thread_b, NULL, thread_b_code, NULL);
pthread_join (thread_a, NULL);
pthread_join (thread_b, NULL);
return 0;
}
In particular, the reason this example is not guaranteed to work to
any definition is that std::cout is a shared library object accessed
via method calls by multiple threads concurrently without an
application-level locking protocol.
Regards,
Loren
More information about the Libstdc++
mailing list