c++ - When to use mutexes? -


i've been playing around gtkmm , multi-threaded guis , stumbled concept of mutex. i've been able gather, serves purpose of locking access variable single thread in order avoid concurrency issues. understand, seems rather natural, still don't how , when 1 should use mutex. i've seen several uses mutex locked access particular variables (e.g.like tutorial). type of variables/data should mutex used?

ps: of answers i've found on subject rather technical, , since far expert on looking more conceptual answer.

if have data accessed more single thread, need mutex. see like

themutex.lock() do_something_with_data() themutex.unlock() 

or better idiom in c++ be:

{     mutexguard m(themutex)     do_something_with_data() } 

where mutexguard c'tor lock() , d'tor unlock()

this general rule has few exceptions

  • if data using can accessed in atomic manner, don't need lock. in visual studio have functions interlockedincrement() this. gcc has it's own facilities this.

  • if accessing data ever read , never change it, it's safe without locking. if single thread change data, other threads need make sure don't try read data while being changed. can read reader-writer lock kind of situations.


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -