基於我剛纔的問題here,我寫一個小班幫我分配工作一堆線程。在構造線程時,我想將循環計數器作爲附加參數傳遞給要用作thread_id的參數包。這可能嗎?包裝附加參數在C可變參數參數包++ 11
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
}
你真的不想轉發rvalue參數*多次*。他們會第一次搬家。 –
建議做什麼? – ruser45381