Saving and the subsequent function of calling an unknown class

I am trying to create a threadpool that can run functions from unknown classes. I do not want to create non-members as a proxy. I managed to create a working class and a workthread class and a task structure, all of which are templates.

// ThreadPool.h
/* Threadpool creates N WorkerThreads (each worker has a ptr to the creating pool), 
    these block until a task is ready then call ThreadPool::doTask() */
template<class T>
struct Task {
    Task() : func(0), inst(0) { }

    Task(boost::function<void(T*)> function, T* instance) : func(0), inst(0) {
        func = function;
        inst = instance;
    }

    void operator()() {
        Task::func(inst);
    }

    T* inst;
    boost::function<void(T*)> func;
};

template<class T>
class ThreadPool {
    template<class T> friend class WorkerThread;
public:

    void addTask(Task<T> task) {
        ... // Some stuff
    }

    bool doTask() {
        Task<T> task;

        ... // Gets a task from std::queue

        // Check the task actually exists!
        if(task.func && task.inst) {
            // Do the task
            (task)();
        }
    }
private:
    std::queue<Task<T>> mTasks;
};

As with this code, I define a class for ThreadPool and Task. But I want to be able to name members of unknown class types. I was considering void ptr, but I could not find a way to convert this to a valid instance of ptr. I also looked at boost :: mem_fun, but struggled to handle it.

I read briefly about C ++ 0x and, as I understand it, it should make it easier to solve my problem, but I would like to solve it before that, if at all possible.

+3
2

T * , boost::function<void ()>?

, , -, .

X ​​ :

poll.add(boost::bind(&X::member, x_instance, other_arguments));

- .

Update:

boost:: function Task. . :

class TaskQueue {
    std::deque<boost::function<void ()> > m_tasks;

public:
    void add(boost::function<void ()> const& f) { m_tasks.push_back(f); }
    bool has_task() const { return !m_tasks.empty(); }
    void do_task() {
        m_tasks.front()();
        m_tasks.pop_front();
    }
};

int example_enqueue(TaskQueue* tq) {
    boost::shared_ptr<RandomClass> rc(new RandomClass);
    tq->add(boost::bind(&RandomClass::method, rc, arg_1, arg_whatever));
}

, , boost:: shared_ptr, , , . .

+3
0

All Articles