newbie thread synchronization question
I'm a total newbie with the Thread library, so please forgive me if this is a dumb question. Say I make a class called Shared that looks something like this: class Shared { private: boost::mutex monitor; int qty; public: Shared() : qty(0) { } void lock() { monitor.lock(); } void unlock() { monitor.unlock(); } int getQty() { return qty; } void setQty(int q) { qty = q; } }; If I use it in from multiple threads with code that looks like: // s is an instance of Shared s.lock(); int q = s.getQty(); ++q; s.setQty(q); s.unlock(); will it work reliably on a multi-core machine? When the mutex unlock() happens, does that flush the CPU cache and write the value of s.qty to main memory? Does the mutex lock() operation clear the CPU cache and force a reload of s from the main memory? I'm trying to understand how synchronization works among multiple cpus. I've only worked on multithreaded code in Java and there the memory model is well defined. AFAIK, that isn't the case in C++. Cory
will it work reliably on a multi-core machine? When the mutex unlock() happens, does that flush the CPU cache and write the value of s.qty to main memory? Does the mutex lock() operation clear the CPU cache and force a reload of s from the main memory? I'm trying to understand how synchronization works among multiple cpus.
I've only worked on multithreaded code in Java and there the memory model is well defined. AFAIK, that isn't the case in C++.
I have never encountered a C/C++ thread library which would not reliably work on multi core systems. libpthread works well and I assume boost uses libpthread as underlying base (at least on unix based systems).
If I use it in from multiple threads with code that looks like: // s is an instance of Shared s.lock(); int q = s.getQty(); ++q; s.setQty(q); s.unlock();
It's correct locking, but if getQty/setQty throw, the object never gets unlocked. So it's worth useing some RAII-style technique.
participants (3)
-
Cory Riddell
-
Igor R
-
Rudolf Leitgeb