简体   繁体   中英

c++ pass function to thread pool

I am practising with threads and thread concurrency and I want to make my own thread pool. For this I have a vector of threads, those threads will wait on a condition variable to get the next function to execute from another vector.

But I have troubles storing/passing/executing functions with unknown arguments. Can someone please give me a hint how to do this or what i need for this?

working EDIT:

Adding task:

ThreadPool tp(10);
tp.execute(std::bind(print, i));

void print(int i) {
    std::cout << i << std::endl;
}

void ThreadPool::execute(const std::function<void()> function) {
    l.lock();
    if (running) {
        queue.push_back(function);
        cv.notify_one();
    } else {
        // TODO error
        std::cout << "err execute()\n";    
    }
    l.unlock();
}

Thread loop:

// set up threads in constructor
for (int i = 0; i < size; i++) {
   threads.push_back(std::thread(&ThreadPool::thread_loop, std::ref(*this), i));
}

static void ThreadPool::thread_loop(ThreadPool &pool, int id) {
    pool.o.lock();
    std::cout << "pool-" << pool.id << "-thread-" << id << " started\n";
    pool.o.unlock();
    std::function<void()> function;
    std::unique_lock<std::mutex> ul(pool.m, std::defer_lock);

    while (pool.running || pool.queue.size() > 0) {
        ul.lock();
        while (pool.queue.size() == 0) {
            pool.cv.wait(ul);
        }
        pool.l.lock();
        if (pool.queue.size() == 0) {
            pool.l.unlock();
            continue;
        }
        function = pool.queue.at(0);
        pool.queue.erase(pool.queue.begin());
        pool.l.unlock();
        ul.unlock();
        function();
    }
}

You need to add the function + its arguments as variadic template:

template<class Task, class ...Args>
void ThreadPool::execute(Task&& task, Args&& ... args) {
    l.lock();
    if (running) {
        queue.emplace_back(std::bind(std::forward<Task>(task),std::forward<Args>(args)...));
        cv.notify_one();
    } else {
        // TODO error
        std::cout << "err execute()\n";    
    }
    l.unlock();
}

Example use:

ThreadPool tp(/*whatever you pass the thread pool constructor*/);
tp.execute(printf,"hello from the threadpool.");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM