当我试图用线程编译程序时,C2672错误('voke':找不到匹配的重载函数)正在发生。
我的代码:
#include <iostream>
#include <thread>
// the procedure for array 2 filling
void bar(int sum2)
{
for (int i = 100000; i < 200000; i++) {
sum2 = sum2 + (i + 1);
std::cout << sum2;
}
}
int main()
{
// the second counter initialization
int sum2 = 0;
// the constructor for the thread
std::cout << "staring thread2...n";
std::thread thread(bar);
// the thread detaching
thread.detach();
// the first counter initialization
int sum1 = 0;
// filling of the first array
for (int i = 0; i < 100000; i++) {
sum1 = sum1 + (i + 1);
// elements output
std::cout << sum1;
}
}
请告诉我,如何修复这个bug?
您需要将一个值传递给正在创建的线程
std::thread thread(bar, N);
其中N是整数值,正如您在void bar(int)
函数中定义的那样。
#include <iostream>
#include <thread>
// the procedure for array 2 filling
void bar(int sum2)
{
for (int i = 100000; i < 200000; i++) {
sum2 = sum2 + (i + 1);
std::cout << sum2;
}
}
int main()
{
// the second counter initialization
int sum2 = 0;
// the constructor for the thread
std::cout << "staring thread2...n";
std::thread thread(bar, 100);
// the thread detaching
thread.detach();
// the first counter initialization
int sum1 = 0;
// filling of the first array
for (int i = 0; i < 100000; i++) {
sum1 = sum1 + (i + 1);
// elements output
std::cout << sum1;
}
return 0;
}
OP函数bar()
的签名为:
void bar(int sum2)
因此,当函数传递给std::thread
时,需要一个参数来初始化bar()
函数参数int sum2
。
当std::thread
尝试在内部调用bar()
时,它在没有任何参数的情况下这样做,但在没有参数的情况中不会重载bar()
。因此,错误
C2672 error ('invoke': no matching overloaded function found)
它应该是std::thread thread(bar, sum2);
或std::thread thread(bar, 0);
或类似的东西而不是std::thread thread(bar);
。
OP的固定示例(包括其他一些小调整):
#include <iostream>
#include <sstream>
#include <thread>
// the procedure for array 2 filling
void bar(int sum2)
{
for (int i = 10/*0000*/; i < 20/*0000*/; i++) {
sum2 = sum2 + (i + 1);
std::cout << (std::ostringstream() << " 2: " << sum2).str();
}
}
int main()
{
// the second counter initialization
//int sum2 = 0; // UNUSED
// the constructor for the thread
std::cout << "staring thread2...n";
std::thread thread(bar, 0);
// the thread detaching
thread.detach();
// the first counter initialization
int sum1 = 0;
// filling of the first array
for (int i = 0; i < 10/*0000*/; i++) {
sum1 = sum1 + (i + 1);
// elements output
std::cout << (std::ostringstream() << " 1: " << sum1).str();
}
}
输出:
staring thread2...
1: 1 1: 3 1: 6 1: 10 1: 15 1: 21 1: 28 1: 36 1: 45 1: 55 2: 11 2: 23 2: 36 2: 50 2: 65 2: 81 2: 98 2: 116 2: 135 2: 155
coliru 上的现场演示