c++ - What are the differences between those two approaches of threading? -


i going implement job based threading architecture. means on 1 hand, there queue main thread can append jobs to. on other hand there worker threads, dependent on number of available cpu cores, consuming jobs , removing them queue.

now, there 2 approaches implement in c++ coming mind. first 1 template based. there task template representing 1 job. holds function, might lamda , provides access data.

to use this, we'd have store in work function object, lambda expression. moreover, need point data pointer our data object , set empty false after that. of course object must attached job queue. worker thread fetching job lock access, , main thread can check lock free every time work result then.

template <class t> class task { public:     task()     {         empty.store(true);         data = nullptr;     }     std::mutex access;     std::atomic<bool> empty;     std::function<void(t*)> work;     t *data; }; 

the second approach inheritance based. empty flag , mutex remain in first approach. work function real method wants overridden. furthermore, don't need data pointer anymore since derived task can add whatever members wants to.

class task { public:     task()     {         empty.store(true);         data = nullptr;     }     std::mutex access;     std::atomic<bool> empty;     virtual void work() = 0; }; 

just make more clear, here 2 short examples of how start jobs within main thread. let's start first one.

int number;  task<int> *example = new task<int>(); example.data = &number; example.empty.store(false); example.run = [](int* number){     *number = 42; });  queue.push_back(example); 

and second approach.

class example : public task { public:     example(int *number)     {         this->number = number;     }     void work()     {         *number = 42;     }     int number; };  int number;  example *example = new example(&number);     example.empty.store(false);  queue.push_back(example); 

what difference in performance , flexibility of 2 approaches?

the first example lets use arbitrary thread function without having define entirely new class it. main issue, however, must allocate memory user data pass thread function. task should take integer, still have pass pointer it.

the second approach, however, lets add number of members of size task, , gives private access actual task instance, may beneficial later on. furthermore, because not templated, it's easier maintain list of task instances.

as far performance concerned, they're pretty same, since virtual functions implemented function pointers.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -