Skip to content

SO 5.7 InDepth Custom Worker Threads

eao197 edited this page Dec 27, 2021 · 18 revisions

What Is It?

Until v.5.7.3 there wasn't a possibility to specify a custom thread to be used by SObjectizer dispatchers. But sometimes such a feature could be useful. For example, a specific thread stack size has to be set by pthread_attr_setstacksize in POSIX Thread, or some signal handlers have to be set for a new worker thread on Unix. But SObjectizer created worked thread by itself by using std::thread and didn't provide a way to tune new worker threads.

Since v.5.7.3 it is possible to instruct SObjectizer to use custom worker threads. This feature is based on two interfaces added in v.5.7.3: so_5::disp::abstract_work_thread_t and so_5::disp::abstract_work_thread_factory_t.

Since v.5.7.3 a user can define his/her own worker thread type by implementing so_5::disp::abstract_work_thread_t interface. The user also has to define own thread factory by implementing so_5::disp::abstract_work_thread_factory_t interface. An instance of such a factory has to be created and specified in the params to a SObjectizer dispatcher or to the whole SObjectizer Environment.

abstract_work_thread_t Interface

A user has to define his/her own class that inherits so_5::disp::abstract_work_thread_t type and implements its pure virtual methods.

At the moment so_5::disp::abstract_work_thread_t defines just two virtual methods that have to be implemented in a derived class:

virtual void start( body_func_t thread_body ) = 0;
virtual void join() = 0;

where body_func_t is defined that way:

using body_func_t = std::function< void() >;

Method start has to start the execution of thread_body in the context of a separate thread. There are no limitations: it can be a newly created thread or preallocated one. There is no need to guarantee that thread_body is already started its execution before the return from start, but it is required to guarantee that all required resources are allocated and thread_body has been passed to a separate execution context.

It should also be guaranteed that join can safely be called just after the return from start.

The join method is an analog of std::thread::join: once called in should return only when the separate execution context finished the execution of thread_body passed to the previous call to start.

SObjectizer guarantees that join is called for a thread only once after the successful call to start. If start throws then join isn't called.

Exception Safety For Implementations Of abstract_work_thread_t

Clone this wiki locally