gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:45:06 29 4
gpt4 key购买 nike

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

但是我在存储/传递/执行带有未知参数的函数时遇到了麻烦。有人可以给我提示如何执行此操作或我需要什么吗?

工作编辑:

添加任务:

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

关于c++将函数传递给线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40322860/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com