【问题标题】:trying Multithreading in a class (c++11) [duplicate]在类中尝试多线程(c ++ 11)[重复]
【发布时间】:2014-07-19 03:35:05
【问题描述】:

我正在尝试使用多线程多次调用其他方法(即在同一个类中)的方法创建一个类。代码是这样的:

#include <iostream>
#include <thread> 
using namespace std;

class ThreadedMatcher
{
    float Match()
    {
        thread t[5];
        //5 is just as an aleatory number
        //The error doesn't change if I use a pointer (like thread *t;)
        for (int i = 0; i < num_jobs; i++)
        {
            t[i](partialMatch,i);
        }
    }

    void partialMatch(int i){
        //Whathever I put in here doesn't change the error
    }
}

(这段代码写在“ThreadedMatcher.h”中)

当我编译这个时,会出现接下来的两个错误:

错误 c3867: 'ThreadedMatcher::partialMatch': 函数调用缺少参数列表;使用 '&ThreadedMatcher::partialMatch' 创建指向成员的指针

错误 c2064:术语不计算为采用 2 个参数的函数

(这两个错误是指for bucle里面的部分)

如果我遵循第一个错误中的建议,则第二个错误仍然存​​在。

谁能告诉我如何解决这个问题?我在 Windows 8 中使用 Visual Studio 2012 (c++11)。

感谢您提供的任何帮助。

PS:对不起我的英语不好,我已经尽力了

【问题讨论】:

  • @WilliamCustode 仅限static void partialMatch(int i);

标签: c++ multithreading c++11


【解决方案1】:

要引用类中的函数,您必须引用该函数所在的类。

将您的线程执行更改为通过引用传递。

This SO question

解释得很好

从那个问题

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

【讨论】:

  • 这不是和按照第一个错误代码中的建议一样吗?正如我所说,当我这样做时,第二个错误仍然存​​在。你知道怎么解决吗?
  • @n0b0dy1 你是否也将指针传递给this
  • 你的意思是像“t[i](&ThreadedMatcher::partialMatch, this,i);”?如果是这样,是的,我做到了。
猜你喜欢
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 2013-07-16
相关资源
最近更新 更多