Jim Meyering wrote: > Thomas Rast wrote: > > [GCC moves access to a file-static variable across pthread_mutex_lock()] > > Thanks for the investigation. > Actually, isn't gcc -O2's code-motion justified? > While we *know* that those globals may be modified asynchronously, > builtin/grep.c forgot to tell gcc about that. I'm somewhat unwilling to believe that: * "volatile" enforces three unrelated things, see e.g. [1]. * Removing "static" would do the same as it prevents the compiler from proving at compile-time that pthread_mutex_lock() cannot affect the variable in question. If this is correct, it also means that all code in all pthreads tutorials I can find works merely by the accident of not declaring their variables "static". Furthermore, a future smarter compiler with better link-time optimization might again prove the same and eliminate the "superfluous" load. However, as a result of the discussion I now have a shorter testcase: #include <pthread.h> int y; static int x; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; void test () { y = x; pthread_mutex_lock(&m); x = x + 1; pthread_mutex_unlock(&m); } GCC 4.6.1 on F16 again assumes 'x' was not modified across the lock. I also tested GCC 4.5.1 and 4.4.5, which instead issue a direct add-to-memory instruction addl $1, x(%rip) in the locked part. In the event that you and GCC 4.6.1 are right, I still vote for removing 'static' instead of adding 'volatile' so as to allow basic optimizations. -- Thomas Rast trast@{inf,student}.ethz.ch -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majordomo@xxxxxxxxxxxxxxx More majordomo info at http://vger.kernel.org/majordomo-info.html