C++ 基本多线程故障排除

标签 c++ multithreading templates

每当我尝试编译这个程序时,我都会收到错误:“错误 C2661:'std::thread::thread':没有重载函数需要 7 个参数”。当我尝试用

制作线程时,我得到了这个
genparts<T>

或者只是

genparts.

目前我正在尝试熟悉线程,因为它的值(value)。

我知道我不应该有一个传递了这么多参数的函数,最好是传递一个包含这些信息的结构——这是我会在一切都准备好后解决的问题和运行。

template <typename T>
void genparts(unsigned int target, unsigned int &total, unsigned int low, unsigned int high, map<unsigned int, unsigned int> container, T gen){
return;}

还有一个调用函数:

void genpart(unsigned int target, map<unsigned int, unsigned int> &container, T& gen){
unsigned int total[2];
map<unsigned int, unsigned int> results[2];
do{
    total[0]=0;
    total[1]=0;
    thread t1(genparts<T>, target, total[0], 1, target/2, results[0], gen);
    thread t2(genparts<T>, target, total[1], 1+(target/2), target, results[1], gen);
    t1.join();
    t2.join();
}while(total[0]+total[1] != target);
}

非常感谢您的帮助!谢谢!

最佳答案

很多细节都是错误的...比如您传递的参数数量(容器去哪儿了?),并且您一直在制作 map 的拷贝。但最重要的是,需要通过引用传递给线程函数的参数需要包装在 std::ref 中。将它们放在一起,这是一个“有效”的版本:

#include <map>
#include <thread>

template <typename T>
void genparts(unsigned int target, unsigned int &total,
              unsigned int low, unsigned int high,
              std::map<unsigned int, unsigned int>& container, T& gen)
{ /* ... */   }

template <typename T>
void genpart(unsigned int target,
             std::map<unsigned int, unsigned int> &container, T& gen)
{
  unsigned int total[2];
  std::map<unsigned int, unsigned int> results[2];
  do
  {
    total[0] = 0;
    total[1] = 0;
    std::thread t1(genparts<T>, target, std::ref(total[0]), 1,
                   target / 2, std::ref(container), std::ref(gen));
    std::thread t2(genparts<T>, target, std::ref(total[1]), 1 + (target / 2),
                   target, std::ref(container), std::ref(gen));
    t1.join();
    t2.join();
  } while (total[0] + total[1] != target);
}

关于C++ 基本多线程故障排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22313974/

相关文章:

c++ - Type Traits - 显式模板特化。在 xcode 上失败

.net - 从 .NET 转向 Win32 开发

c++ - 在 C++ 中倒带 ifStream

java - 如何绑定(bind)swing.JTextArea到PrintStream接受数据

windows - 拥有多个线程池与单个线程池相比有什么好处?

c++ - 使用模板检查结构中的字段,启用函数,如果失败则给出错误消息?

c++函数作为模板参数

c++ - 普通比较时QT 4.8崩溃

c++ - 在 C++ 中创建 pacman 碰撞检测的困难

Android - 如何在另一个 Activity 期间暂停线程?