當我嘗試使用執行緒編譯程式時,出現 C2672 錯誤('invoke':未找到匹配的多載函式)。
我的代碼:
#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;
}
}
請告訴我,如何修復這個錯誤?
uj5u.com熱心網友回復:
您需要將一個值傳遞給您正在創建的執行緒,
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;
}
uj5u.com熱心網友回復:
OPs 函式的簽名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);應該是std::thread thread(bar, sum2);或std::thread thread(bar, 0);或類似的東西。
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 上進行現場演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/533127.html
標籤:C 多线程c 20调用
