繁体   English   中英

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

[英]c++ pass function to thread pool

我正在使用线程和线程并发进行练习,我想创建自己的线程池。 为此,我有一个线程向量,这些线程将等待条件变量以从另一个向量获取要执行的下一个函数。

但是我在使用未知参数存储/传递/执行函数时遇到了麻烦。 有人可以给我提示如何做到这一点或我需要什么吗?

工作编辑:

添加任务:

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();
}

线程循环:

// 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();
    }
}

您需要将函数及其参数添加为可变参数模板:

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();
}

使用示例:

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