c - Operations from atomic.h seem to be non-atomic -
The following code generates random values for both n and v. It is not surprising that n is random without properly preserved but it is believed that v is ultimately to be 0. Is there anything wrong with my code? Or can this explain to me this? Thank you.
I am working on a 4 core server of x86 architecture. The only one as follows.
Linux 2.6.9-22.ELsmp # 1 SMP Mon 19 September 18:00:54 EDT 2005 x86_64 x86_64 x86_64 GNU / Linux
# include & lt ; Stdio.h & gt; # Include & lt; Pthread.h & gt; # Include & lt; Asm-x86_64 / atomic.h & gt; Int n = 0; Atomic_t v; Pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; #define LOOP 10000 Zero * foo (Zero * P) {int i = 0; (I = 0; i & lt; loop; i ++) for {// pthread_mutex_lock (and mutex); ++ n; --n; Atomic_inc (& amp; v); Atomic_dec (& amp; v); // pthread_mutex_unlock (and mutex); } Return tap; } #DIFTIN COUNT 50 IND Main (Int ARRAKAK, FOUR ** argv) {int i; Pthread_t pids [COUNT]; Pthread_attr_t attr; Pthread_attr_init (& amp; attr); Atomic_set (& amp; v, 0); {Pthread_create (& pids [i], & amp; attr, foo, NULL) for i (i = 0; i
Can we see the codeal output of code (GCC-E, me looks like). Even thought that uname it indicates SMP-aware, does not mean that it has been compiled with CONFIG_SMP.
Without it, the lock prefix is not in the assembler code output, you can interfere your core with each other.
But I am using pthread functions because they are portable on more platforms.
Comments
Post a Comment