How to call class methods on a background thread using CThreadPool

  atl, c++, threadpool, winapi

Let’s say you have some sort of class, and you’d like to call some of its methods on a background thread. That’s what I’m interested in, and I thought CThreadPool would be a nice thing to use for this. I was wondering if anyone has used CThreadPool for method calls before.

So here’s what I’ve set up. Based on this example from Microsoft, I’ve created an abstract "task" class (which I’ve denoted as an interface), as well as a worker class:

class ITask
{
public:
    virtual void DoTask(LPVOID, LPOVERLAPPED) = 0;
};

class CWorker
{
public:
    typedef DWORD_PTR RequestType;

    BOOL Initialize(LPVOID)
    {
        return TRUE;
    }

    void Execute(RequestType dw, LPVOID pvParam, LPOVERLAPPED pOverlapped) throw()
    {
        ITask* pTask = (ITask*)(DWORD_PTR)dw;
        pTask->DoTask(pvParam, pOverlapped);
    }

    void Terminate(LPVOID)
    {
    }
};

Then in my main class, I essentially do this:

class MyClass
{
public:
    MyClass()
    {
        m_threadpool.Initialize(this, NUM_OF_THREADS_DESIRED);
    }
    ~MyClass()
    {
        m_threadpool.Shutdown();
    }

private:
    CThreadPool<CWorker> m_threadpool;
    
    class : public ITask
    {
    public:
        void DoTask(LPVOID pvParam, LPOVERLAPPED)
        {
            MyClass* pObj = (MyClass*)pvParam;
            pObj->MethodToCallOnBackgroundThread();
        }
    } m_task;

    void MethodForQueuing()
    {
        m_threadpool.QueueRequest((CWorker::RequestType)&m_task);
    }

    void MethodToCallOnBackgroundThread()
    {
        // Do something
    }
};

This seems to work. One drawback is that it requires declaring a new ITask-derived class for every method that you’d like to use the threadpool for, but that’s apparently how the Microsoft example works. I guess another approach would be to create a more generic task object and then pass in an enum or something, which can be used for a switch statement within a class method. Anyway, has anyone dealt with this situation, and if so, do you have any input?

Source: Windows Questions C++

LEAVE A COMMENT