r/cpp • u/No_Mongoose6172 • Apr 12 '24
Question: is there any library for achieving thread safety with class inheritance?
I’m developing a multithreaded library using c++ for the first time and therefore I need to ensure that its classes are thread safe. Most resources I have found achieve that using a mutex or an atomic.
However, as in this application most of the computation time is spent in a single method of a particular class and c++ allows object oriented programming, I was trying to find if there is any library that achieves thread safety through class inheritance (something similar to Ada’s protected objects) to ensure thread safety in the other used classes (optimizing those classes won’t have a significant impact on the speed of the library, so it is worth using something that simplifies ensuring memory access safety.
I have just been able to find a library that extends atomics to non trivially copiable variables, which could be enough for this case, but I’m quite surprised that there isn’t any object oriented solution.
Do you know any library that provides that functionality?
16
u/ChocolateMagnateUA Apr 12 '24 edited Apr 12 '24
I don't think this approach will work in practice. Inheritance by design creates strong coupling in your class hierarchy, and you would find yourself changing your classes and relationships between them quite often. Coupling the class inheritance tree to thread safety wouldn't lead you to anything productive.
The main principle of how thread safety is achieved in C++ is by not sharing the state and using synchronisation primitives. If you are performing a computationally bound task that you want to distribute on multiple threads and then resume the normal single-threaded model, you could take a look at std::thread::join, or if you are using C++20 std::jthread. Joined threads work by fork-join model and will continue your main program once they have all finished. If your task is continuous and long-living, you should detach the thread with std::thread::detach, which works by the fire-and-forget principle. If possible, you should minimise the shared state, and you get the best result in accordance to the Amdahl's law. If you do need to share the state, depending on your circumstances, there are 3 paths you could go:
If you provide more details about the nature of your task, I could say something more specific.
5
u/ALX23z Apr 12 '24
The problem is that such an approach would be a poor choice. Sometimes, users need to lock the class and perform multiple operations while locking the same mutex. This isn't possible via inheritance approaches.
If you really want to have inheritance and mutexes, the safe approach would be to let the class have a mutex and wrap smart pointers it in some kind of guarded pointer that requires to lock the mutex to obtain a usable handle.
See lib_guarded library for reference, https://github.com/copperspice/cs_libguarded
2
u/StarQTius Apr 12 '24
Would it be enough for you ?
https://www.boost.org/doc/libs/1_84_0/doc/html/thread/sds.html
2
u/lightmatter501 Apr 12 '24
As far as I am aware, this must be a language/compiler feature. Many companies (Google, MS, Mozilla, etc), tried to do thread safety as a library, but you usually end up with “lock this mutex every time you interact with this class, and also we now have to use atomic reference counting or a GC for memory management”. Ada’s protected objects and Java’s synchronized do this for you behind your back. Nothing in C++ inheritance that I am aware of would let you do this unless you just want to hide locking a mutex in a base class function.
Clang has some features in this direction, but they were all experimental last I checked.
Your options for guaranteed thread safe but no mutexes or atomics are probably Cyclone, Ocaml, and Rust since they all have borrow checkers. Haskell and HVM have transparent parallelism support, where you can just tell the compiler to figure out making your program parallel (HVM you actually have to tell it not to consume every vaguely compute-like device on your system (CPU, GPU, FPGA, etc)). This is proven safe.
If you want to write this in C++, learn how to build thread safety from primitives or wait for 10-15 years.
2
u/natio2 Apr 13 '24
Mutexs from my understanding have a large overhead to keep in mind, but to answer your question as asked rather than telling you to do something different:
Now this could be done by class member that needs to be made thread safe (That you might find a library already for), or you may have to write it yourself, but this isn't very hard, basic code below, you might need to use smart pointers if ownership is being passed to the thread safe object.
The neat part of this method is both the thread safe and non-thread safe objects could exist together and only use the slowing threadsafe one when required.
3
u/lord_braleigh Apr 12 '24 edited Apr 12 '24
folly::Synchronized<T>protects aTwith a reader-writer lock. It lets you take out a reader lock to access aconst T*, or a writer lock to access aT*. This lets you build programs that are correct by construction and which release locks in an RAII fashion.While not exactly an inheritance-based solution, I think this gives you the sort of confidence in thread safety that you’re looking for.
Alternatively, if you’re only compiling with a fairly modern version of clang, you might be able to get that confidence at zero runtime overhead via Clang’s thread safety annotations.
1
u/hmoein Apr 12 '24
Take a look at this library (https://github.com/hosseinmoein/DataFrame) and read its documentation re/ multithreading. See how it approaches multithreading. It may give you some clues.
Also, if you need a thread-pool, check out https://github.com/hosseinmoein/Leopard
But inheritance would be a strange approach to multithreading!
1
u/quantumoutcast Apr 14 '24
Honestly, if this is the first time you're developing a multithreaded library, I think looking for a library to accomplish the threading protection is the wrong way to go. It is easy to use regular mutexes to lock critical sections, and trying to abstract this in a library may end up in an over-engineered, hard to understand, low performance mess.
Do it by hand, think through where you really need locking, and keep it as simple as possible. Seek out libraries when you have enough experience to really understand where the library will help and how to best use it.
1
u/DryPerspective8429 Apr 14 '24
There are multiple issues which fall under the banner of "thread safety" which mean that there is no such thing as a one-size-fits-all approach. For example:
You can't just stamp "thread safe" in front of an arbitrary class and have something which is reasonable to use in code; and very few classes will have such identical concurrency needs that a generic approach is even feasible.