简体   繁体   中英

Qt example: no mutex lock when reading, why?

I am looking at this example, and it raises a queston for me: when looking at this file a mutex is being used when accessing the global variable m_abort when its being changed. But when the run method reads from it, it does nothing with the mutex at all. Why?

Well, I cannot see the purpose of the mutex at all. Both reading and writing m_abort can be performed without mutex protection as it's a bool variable, and its value is changed atomically (at least on most platforms). And even if the write itself is not atomic and the variable can have an inconsistent value - it can be either false or true, and it will eventually be read as true (since the only value that is written there is true ).

Will work most of the time, but isn't the correct thing to do. It should be locked.

Also, check Is Mutex required for 1 byte shared memory for further information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM