C++ 如何解决Visual Studio目录中的线程文件错误?
我编写了这个小程序,使用5个线程来输出ID和等待延迟时间。当我试图执行程序时,编译器抛出错误: 错误C2672'std::invoke':未找到匹配的重载函数 和 C2893未能专门化函数模板“未知类型std::invoke(_Callable&&,_Types&&…)noexcept()” 它说它们都在VisualStudio目录中include文件夹的线程文件的第39行。 我试图在网上查找解决方案,但运气不佳。您是否能够帮助确定问题 这是我的代码供参考:C++ 如何解决Visual Studio目录中的线程文件错误?,c++,multithreading,visual-studio,invoke,C++,Multithreading,Visual Studio,Invoke,我编写了这个小程序,使用5个线程来输出ID和等待延迟时间。当我试图执行程序时,编译器抛出错误: 错误C2672'std::invoke':未找到匹配的重载函数 和 C2893未能专门化函数模板“未知类型std::invoke(_Callable&&,_Types&&…)noexcept()” 它说它们都在VisualStudio目录中include文件夹的线程文件的第39行。 我试图在网上查找解决方案,但运气不佳。您是否能够帮助确定问题 这是我的代码供参考: // Multithreading
// Multithreading example
// Michal Baran
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
// Import things we need from the standard library
using std::chrono::milliseconds;
using std::cout;
using std::endl;
using std::ofstream;
using std::this_thread::sleep_for;
using std::thread;
using std::vector;
using std::move;
//Declare a struct
struct ThreadArgs
{
int id{};
int delay{};
};
//Thread function, prints out thread id and wait delay time 10 times
void myThreadFunc(struct ThreadArgs *args)
{
for (int i = 0; i < 10; i++)
{
cout << "This is id: " << args->id << endl;
sleep_for(milliseconds(args->delay));
cout << "Wait time: " << args->delay << "ms. " << endl;
}
}
int main(int argc, char *argv[])
{
// Declare an instance of a struct here
ThreadArgs args;
//Assign values into struct, starting with id 0 and delay 500 and rising up to id 5 and delay 900
for (int t = 0; t < 5; t++)
{
int id = -1;
int delay = 400;
ThreadArgs th{ id=+1, delay=+100 };
}
//Create a vector to hold threads
vector<thread> vecOfThreads;
//Add thread object to vector
vecOfThreads.push_back(thread(myThreadFunc));
//Loop 5 times to create a thread and move it to the vector
for (int t = 0; t < 5; t++)
{
thread th(myThreadFunc, &args);
vecOfThreads.push_back(move(th));
}
// Wait for threads to finish and join them
for (thread& th : vecOfThreads)
{
if (th.joinable())
th.join();
}
return 0;
}
//多线程示例
//米查尔·巴兰
#包括
#包括
#包括
#包括
//从标准库导入我们需要的东西
使用std::chrono::毫秒;
使用std::cout;
使用std::endl;
使用std::of流;
使用std::this_线程::sleep_for;
使用std::线程;
使用std::vector;
使用std::move;
//声明结构
结构线程参数
{
int-id{};
int延迟{};
};
//线程函数,打印线程id和等待延迟时间10次
void myThreadFunc(结构线程参数*args)
{
对于(int i=0;i<10;i++)
{
coutstd::invoke
函数无法编译,因为您给它的参数无效
//Add thread object to vector
vecOfThreads.push_back(thread(myThreadFunc));
不确定您打算在那里做什么,但是您正在尝试使用myThreadFunc
函数创建一个新线程,但没有为它提供所需的参数
如果您只想在之前创建一个线程,以后再运行它,那么没有必要这样做。线程在构建时会立即启动,如果您想创建一个占位符,只需使用默认构造函数。不过,这似乎不是您想要做的。省略这一行似乎是最好的主意(除非这只是一个片段,而实际的事情做得更多)。从线程构造函数中删除myThreadFunc使这项工作得以完成。谢谢!@MichalBaran还注意到,这意味着将有一个线程对象(在您发布的示例中)永远不用,这意味着你可以删除整个线路。我很高兴你得到了你的解决方案,感谢你的分享。如果你将它们标记为答案,我将不胜感激,这将有利于其他社区。