我正在练习线程和线程并发,我想创建自己的线程池。为此,我有一个线程向量,这些线程将在条件变量上等待从另一个向量执行下一个函数。
但是我在使用未知参数存储/传递/执行函数时遇到了麻烦。有人可以给我一个提示如何做到这一点或我需要什么吗?
正在编辑:
添加任务:
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();
}
}
答案 0 :(得分:0)
您需要将函数+其参数添加为可变参数模板:
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.");