Steve Loughran wrote: >>Lilantha Darshana wrote:
>> Hi C++ team, >> >> A static variable in a class or method is effectively global - all threads >> can access the same variable >> at the same time. If they do, collision can corrupt that variable's value. >putting on my C++ hat for a moment >(http://www.iseran.com/Win32/CodeForSpeed/multithreading.html), I feel >obliged to clarify this. >If your variables are compiled with an alignment that stops it spanning >CPU words, (i.e. int32s aligned on a 4 byte boundary), then single >writes will be atomic and not corrupting. Multi CPU systems do fancy >cache-coherence tricks to ensure that all CPUs have a vague idea what is >happening, so the consequence of such a write is to invalidate the >entire cache line on all CPUs -even read-only items in the same 32+ byte >cache line will need to be retrieved from the last CPU that changed >anything in the block. To elaborate little bit about variable corruption for multithreaded programs for single word (32, 64 etc.) variables, is the *point of view of a given thread*. This is where race conditions can cause if you don't have any locking mechanism applied even though the access to that object is atomic. What If a class wide global static variable is required to have some value for a given thread within a given time frame of its execution & they should changed only by that thread and until that get killed. So having a mutex on such thread, blocks others on performing their tasks. If there is *no sharing required* we can make that variable thread local. >Perhaps std::string is implemented such that you need to write to >1 >address to update a string, in which case race conditions can leave the >system in an indeterminate state. Template classes like std::string are thread safe as far as they are not shared between threads. If they are global it could easily be corrupted due to its memory allocation/modification scheme. For an example if one thread has the iterator on that string, but other just modify the std::string. The modification can cause memory move etc. and the thread that has the iterator has the invalid pointer at hand. because there is no coherency between iterator and the actual internal memory block, the std::string has, no update happen. >Also, unless you put volatile in front of a variable declaration, the >compiler can and will optimize away reads, which means that changes may >not get picked up. Even without having volatile keyword as type qualifier, globally shared objects like class wide static variables could be updated by other threads and could result corrupted variables. Thanks Lilantha. [EMAIL PROTECTED]
