Intel® Moderncode for Parallel Architectures
Support for developing parallel programming applications on Intel® Architecture.

variable sync on multithread envrioments

Ma_Bo
Beginner
337 Views

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?

[cpp]   volatile int a=0;

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

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

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?

[cpp]   volatile int a=0;

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

   /* thread 2(write) */  
   a = 10;  [/cpp] 
0 Kudos
2 Replies
SergeyKostrov
Valued Contributor II
337 Views
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.

0 Kudos
jimdempseyatthecove
Honored Contributor III
337 Views
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
0 Kudos
Reply