Imagine a functionality of an application that requires up to 5 threads crunching data, these threads use buffers, mutex and events to interact with each other. The performance is critical, and the language is C++.
The functionality can be implemented as one (compilation) unit with one class, and only one instance of this class can be instantiated for the application. The class itself implements 1 of the threads in run() method, which spawns other 4 threads, manages them and gathers them when user closes the application.
What is the advantage of choosing one of the following method over another (please do let me know of any better approach)?
- Add 5 static methods to the class, each running a single thread, mutex and other data shared as static class variables.
- Add 5 global functions (no scope) and use global variables, events and mutex (as if it is C)
- change the pattern entirely, add 4 more classes each implementing one of the threads and share data via global variables.
Here are some thoughts and issues to be considered (please correct them if they are wrong):
- Having threads as class members (static of course), they can rely on the singleton to access non-static member functions, it also gives them a namespace which by itself seems a good idea.
- Using static class methods, the class header file soon will contain many static variables (and other helper static methods). Having to declare variables in the class header file may bring additional dependencies to other units that include the header file. If variables where declared globally they could be hidden in a separate header file.
- Static class variables should be defined somewhere in the code, so it doubles typing declaration stuff.
- Compilers can take advantage of the namespace resolution for more optimized code (as opposed to global variables possibly in different units).
- The single unit can potentially be better optimized, whereas whole program optimization is slow and probably less fruitful.
- If the unit grows I have to move some part of the code to a separate unit, so I will have one class with multiple (compilation) units, is this a anti-pattern or not?
- If using more than one class, each handling one thread, again same question can be made to decide between static methods and global functions to implement the threads. In addition, this requires more lien of code, not a real issue but does it worth the additional overhead?
Please answer this assuming no library such as Qt, and then assuming that we can rely on QThread and implement one thread per run() method.
Edit1: The number of threads is fixed per design, number 5 is just an example. Please share your thoughts on the approaches/patterns and not on details.
Edit2: I have found this answer (to a different question) very helpful, I guess the first approach misuses classes as namespaces. Second approach can be mitigated if coupled with namespace.