So, my task is to pass both vectors char
& int
in the template with two threads.
Why it cannot thread to reading the two containers? Some push will be helpful.
#include <iostream>
#include <thread>
#include <vector>
template<typename T>
void check(std::vector<T> values){
for(T& it : values){
std::cout<< it <<std::endl;
}
}
int main()
{
std::vector<int> int_values = {1,2,3,4,5};
std::vector<char> char_values = {'a','b','c','d','e'};
std::thread th1(check, int_values);
std::thread th2(check, char_values);
th1.join();
th2.join();
return 0;
}
The Error is:
error: no matching function for call to std::thread::thread(<unresolved overloaded function type>,std::vector<int>&)
check
is not the name of a function, it is the name of a template. std::thread
needs a function object so just using check
won't work.
You can use check<int>
to specify the int
specialization of the check
template be used, or you could use a lambda and let the compiler figure it out like
std::thread th1([](const auto & var) { check(var); }, std::ref(int_values));
// or even shorter
std::thread th1([&]{ check(int_values); });
template deduction doesn't work with std::thread
, so use
std::thread th1(check<int>, int_values);
std::thread th2(check<char>, char_values);
Another thing, why do you use pass by value here I think you should change that to be
#include <iostream>
#include <thread>
#include <vector>
#include <functional>
template<typename T>
void check(const std::vector<T> & values){
for(const T& it : values){
std::cout<< it <<std::endl;
}
}
int main()
{
std::vector<int> int_values = {1,2,3,4,5};
std::vector<char> char_values = {'a','b','c','d','e'};
std::thread th1(check<int>, std::ref( int_values ));
std::thread th2(check<char>, std::ref( char_values ));
th1.join();
th2.join();
return 0;
}
and std::ref()
is to enable you to pass by reference because std::thread
copies all args in an internal storage
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.