If I do something like class myclass : public somelibrary::thread
- Are all methods called on
myclassexecuted in their own thread? - Is only
run()executed in its own thread? - For every method to be executed in its own thread, do I have to create a new thread in each method?
Not necessarily. It depends on the design of
somelibrary::thread. In fact, Boost.Thread is not used this way (via inheritance). In that case, you simply create a newboost::threadobject passing in a callable object (functors, function pointers, etc.) into its constructor.However, I haven’t seen any thread library where calling any method on a class derived from
somelibrary::threadspawns a new thread. That is asking for data races, unless everything is somehow synchronized. But then your code would be wasting a lot of time waiting on synchronization primitives. Not to mention that threads are relatively expensive in terms of operating system resources. An application may have at most several threads running at any one time assuming it wasn’t designed by an idiot. Methods on the other hand may be called many, many times during the application running time.Not all thread libraries call a
run()method when running a new thread. For example inBoost.Thread, the entry point isoperator()(). But yes, the entry point runs in its own thread, separate from the calling thread. All methods called byrun(), directly or indirectly, runs in the newly-spawned thread.This is almost certainly not what you actually want in C++, because of the fact that threads are very expensive in terms of operating system resources. You’ll be making your operating system waste time allocating and destroying threads all the time. Even in languages like Erlang, where threads are extremely cheap compared to OS threads, you don’t typically spawn a new thread for every single method. A program running many threads or constantly creating/destroying threads is a sign of a badly-designed program.
Yes, if you want each method to run in its own thread, but again, you almost certainly don’t want this.