简体   繁体   English

C ++将函数传递给线程池

[英]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.");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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