【问题标题】:How can I use std::thread inside a member function to call other member functions? [duplicate]如何在成员函数中使用 std::thread 来调用其他成员函数? [复制]
【发布时间】:2013-07-26 15:13:12
【问题描述】:

我正在尝试使用线程调用我的一些成员函数。假设我有这个

class myclass
{
public:
    myclass();
    double function1();
    void function2();
};

myclass::myclass()
{}


double myclass::function1()
{
    ...
    return a double;
}


void myclass::function2()
{
    //use a  thread to call function 1
    std::thread t(function1);//doesnt work!-wont compile
    std::thread t2(myclass::function1);//doesnt work either -wont compile
    std::thread t3(&myclass::function1);//doesnt work here either - wont compile
}

如何通过 C++ 中另一个成员函数内部的线程调用成员函数? 顺便说一下,我正在使用 Visual Studio 2013 Preview。

更新 2:

我按照我说的做了,现在有些代码部分编译得很好,有些则不能!
这是产生错误的新示例代码:

class xGramManipulator
{
public:
    xGramManipulator();

    void ReadMonoGram();
    void ReadBiGram();

    void ReadMonoGram(double &);
    void ReadBiGram(double &);

    void CreateMonoGramAsync();
    void CreateBiGramAsync();
};

xGramManipulator::xGramManipulator()
{
}

void xGramManipulator::CreateMonoGramAsync()
{
    thread t(&xGramManipulator::ReadMonoGram, this);
}

void xGramManipulator::CreateBiGramAsync()
{
    thread t = thread(&xGramManipulator::ReadBiGram, this);
}

上面的代码(这两个 Async 成员函数)会产生以下错误:
错误信息:

错误 C2661: 'std::thread::thread' : 没有重载函数需要 2 个参数

【问题讨论】:

  • 是什么阻止了您格式化您的问题?您已经成为活跃的 SO 成员将近两年了。此外,“不起作用!”很难描述您的技术问题。请做得更好。
  • @LightnessRacesinOrbit:原因很简单,我只是不小心按了 Enter 并提交了问题,然后我什至尝试格式化它。虽然提交后的秒数被“R. Martinho Fernandes”格式化.
  • 好的,这是一个很好的理由。谢谢。
  • 编辑后的代码示例对我来说编译得很好。不过,请确保您使用 #include <thread> 并使用 std::thread。另外,请不要覆盖您的原始问题并进行更改。你可以追加它,但现在你已经把所有的答案都搞砸了。
  • 好的,包括在内!那么为什么它不能在 Visual Studio 2013 预览版中编译呢?你在哪里编译的?

标签: c++ c++11


【解决方案1】:

std::thread(&myclass::function1, this)

如果你需要消除重载的歧义,你必须明确地转换函数指针:

std::thread(static_cast<void (xGramManipulator::*)()>(&xGramManipulator::ReadMonoGram), this)

【讨论】:

  • 请停止回答明目张胆的骗子!天哪!
  • @LightnessRacesinOrbit:我很年轻,需要代表......而且我并不总是足够清醒地知道是否有骗子:-SI 通常只在我觉得强烈的特定领域发现骗子,比如eof(),输入答案比关闭答案要长得多。
  • @KerrekSB 没关系,无论如何回答问题都没有问题。如果结果是重复的,那不是你的错(答案永远不会伤害任何人)。
  • @Hossein:对,我明白了——如果你有多个重载,你必须明确地消除函数指针的歧义。我添加了那个。
  • @Hossein:这只是转换为您想要的函数类型。查找成员函数类型以获取详细信息。另一个重载的类型是void (xGramManipulator::*)(double)
【解决方案2】:

尝试使用此处描述的 boost::bind 来绑定成员函数的隐式“this”参数:

How to use boost bind with a member function

这将使它成为一个没有参数的函数,您可以使用它来启动一个线程。

【讨论】:

  • Kerrek SB 的答案更好,因为它更容易。
  • 这也是一个实际的答案,而不是超链接。
  • @LightnessRacesinOrbit “这也是一个实际的答案,而不是超链接。” - 但也没有真正解释任何事情,只是提供了 “工作” 代码。
  • 没有必要使用boost::bindstd::bind
  • @ChristianRau:你是对的。
猜你喜欢
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多