Sun Studio 12: C++ User's Guide

11.4.3 Global and Static Data

Global and static data in a multithreaded application are not safely shared among threads. Although threads execute independently, they share access to global and static objects within the process. If one thread modifies such a shared object, all the other threads within the process observe the change, making it difficult to maintain state over time. In C++, class objects (instances of a class) maintain state by the values in their member variables. If a class object is shared, it is vulnerable to changes made by other threads.

When a multithreaded application uses the iostream library and includes iostream.h, the standard streams—cout, cin, cerr, and clog— are, by default, defined as global shared objects. Since the iostream library is MT-safe, it protects the state of its shared objects from access or change by another thread while a member function of an iostream object is executing. However, the scope of MT-safety for an object is confined to the period in which the object’s public member function is executing. For example,


    int c;
    cin.get(c);

gets the next character in the get buffer and updates the buffer pointer in ThreadA. However, if the next instruction in ThreadA is another get call, the libC library does not guarantee to return the next character in the sequence. It is not guaranteed because, for example, ThreadB may have also executed the get call in the intervening period between the two get calls made in ThreadA.

See 11.4.5 Object Locks for strategies for dealing with the problems of shared objects and multithreading.