Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » U++ Library support » U++ MT-multithreading and servers » Use same variable in different threads
Re: Use same variable in different threads [message #30122 is a reply to message #30121] Fri, 10 December 2010 00:26 Go to previous messageGo to previous message
Didier is currently offline  Didier
Messages: 680
Registered: November 2008
Location: France
Contributor
Hi Koldo,

I would add one thing to Honza's explanation: 'Memory bariers'

Actually this is not a thing that is used directly by people but it is necessary to understand all that is going on.

Volatile allows you to access a shared variable not protected by mutex and you will be sure it always has the wright value (the cache on the processor might be different for each thread, so in extreme cases you can get de synchronised values of one variable from time to time ..... ==> bugs impossible to find).
Of course if the variable is larger than the processor bus ... the R/W process will not be atomic so you need a mutex !

Memory barriers are points where the cpu cache is flushed so all the synchronisation problems just disappear
In mutexes, such barriers are used to avoid such problems, and therefore when using a mutex lock/unlock procedure, you protect the resource (and it's memory) but you also flush the cash at each mutex lock/unlock.
So .... when using a mutex there is no need to use volatile it might even slow down you're app.

Finally, to answer you're question:
* if the variable (and it's context !) is just an int or smaller it can be accessed atomically ==> use this method, it's the fastest one (volatile will work in most cases but to be sure use the dedicated functions)
* otherwise you have to use the good old mutex, no may out !
- mutex.lock()
- do you're thing ..R..W....etc
- mutex.unlock()


NB: the volatile/synchronisation problems mostly has effects on programs compiled in O3.

Hope this helps you !

[Updated on: Fri, 10 December 2010 00:29]

Report message to a moderator

 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: OpenMP
Next Topic: Different native pthread.h implementations
Goto Forum:
  


Current Time: Thu May 09 09:28:30 CEST 2024

Total time taken to generate the page: 0.02617 seconds