Event / Task Queue Multithreading C++

前端 未结 8 1106
梦如初夏
梦如初夏 2021-02-04 15:18

I would like to create a class whose methods can be called from multiple threads. but instead of executing the method in the thread from which it was called, it should perform t

8条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 16:10

    For extensibility and maintainability (and other -bilities) you could define an abstract class (or interface) for the "job" that thread is to perform. Then user(s) of your thread pool would implement this interface and give reference to the object to the thread pool. This is very similar to Symbian Active Object design: every AO subclasses CActive and have to implement methods such as Run() and Cancel().

    For simplicity your interface (abstract class) might be as simple as:

    class IJob
    {
        virtual Run()=0;
    };
    

    Then the thread pool, or single thread accepting requests would have something like:

    class CThread
    {
       <...>
    public:
       void AddJob(IJob* iTask);
       <...>
    };
    

    Naturally you would have multiple tasks that can have all kinds of extra setters / getters / attributes and whatever you need in any walk of life. However, the only must is to implement method Run(), which would perform the lengthy calculations:

    class CDumbLoop : public IJob
    {
    public:
        CDumbJob(int iCount) : m_Count(iCount) {};
        ~CDumbJob() {};
        void Run()
        {
            // Do anything you want here
        }
    private:
        int m_Count;
    };
    

提交回复
热议问题