variable sync on multithread envrioments

variable sync on multithread envrioments

The questions are limited to X86/LINUX environment.

1. One thread write a var with a lock,other threads read this var without lock. When the write thread unlocked,Could other threads read the new value immediately?

   volatile int a=0;

   /* thread 1(write) */    
   lock();  
   a = 10;  
   unlock();  

   /* thread 2(read) */  
   printf("%d",a);

2. One thread read a var with a lock,another thread write this var without lock. When the read thread read after write complete,Could it read the new value immediately?

   volatile int a=0;

   /* thread 1(read) */  
   lock();  
   printf("%d",a);  
   unlock();  

   /* thread 2(write) */  
   a = 10;  

3 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.

Quoting Ma Bo

The questions are limited to X86/LINUX environment.

1. One thread write a var with a lock,other threads read this var without lock. When the write thread unlocked, Could other threads read the new value immediately?

...

Yes, as soon as the system scheduler givesother threads execution control.

The reading thread does not necessarily require the lock to read the updated variable.

You would use a lock in cases where the writing thread(s) update multiple variables and where the read requires to read the complete set of updates (without partial interviening updates). You may need the read lock in cases of dependency (e.g. traversing a linked list where nodes can be removed and/or added).

If your shared variable is not volatile then you may require a memory barrier/fence.

Jim Dempsey

www.quickthreadprogramming.com

Leave a Comment

Please sign in to add a comment. Not a member? Join today