Based on my previous question here, I am writing a small class to help me distribute work to a bunch of threads. While constructing the thread I would like to pass a loop counter as an additional parameter to the parameter pack to be used as a thread_id. Is this possible?
qthread.h:
#ifndef QTHREAD_H
#define QTHREAD_H
#include <vector>
#include <thread>
#include <memory>
class qthread
{
std::vector <std::shared_ptr <std::thread>> threads;
public:
// Constructor
template <class Fn, class... Args>
qthread(Fn&& fn, Args&&... args)
{
size_t maxNumThreads = std::thread::hardware_concurrency() - 1;
for(size_t i = 0; i < maxNumThreads; i++)
{
// While constructing the thread I would like to also pass i as a thread_id to the function in the parameter packing
threads.push_back(std::make_shared <std::thread>(std::forward<Fn>(fn), std::forward<Args>(args)...));
}
}
// Destructor
~qthread()
{
for(auto thr_p:threads)
{
thr_p->join();
}
}
};
#endif /* QTHREAD_H */
main.cpp:
#include <iostream>
#include "qthread.h"
void test(const size_t thread_id, int x)
{
for(size_t i=0; i < 1000; i++)
{
x += i;
}
std::cout << "thread: " << thread_id << ", total: " << x << "\n";
}
int main()
{
qthread(test, 5); // Distribute the 'test' task to n threads -- note that this doesn't work in this case since the function requires two parameters
}
Aucun commentaire:
Enregistrer un commentaire