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 post / 0 nuovi
Ultimo contenuto
Per informazioni complete sulle ottimizzazioni del compilatore, consultare l'Avviso sull'ottimizzazione

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

Lascia un commento

Eseguire l'accesso per aggiungere un commento. Non siete membri? Iscriviti oggi