多线程 - 类中的异步线程

时间:2014-01-09 16:47:36

标签: c++ multithreading c++11

我有一个类Foo,它有一个主函数和执行函数。我想用execute函数启动一个未知数量的线程,但是当我尝试编译代码时,我总是得到error C2064: term does not evaluate to a function taking 1 arguments

foo.h中

#ifndef BOT_H
#define BOT_H

#pragma once
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <string>
class foo
{
public:
    foo(char *_server, char *_port);
    ~foo(void);
private:
    char *server;
    char *port;

    void execute(char *cmd);
    void main();
};

#endif

foo.c的

#include <thread>
#include "bot.h"
#include "definitions.h"

using namespace std;
foo::foo(char *_server, char *_port){
        ...
}

bot::~bot(void) {
        ...
}
void bot::execute(char *command){
    ...
}
    void bot::main(){
        thread(&bot::execute, (char*)commanda.c_str()).detach();
    }

我应该如何从类成员函数创建线程?

感谢您的回答

1 个答案:

答案 0 :(得分:5)

您需要一个bot对象来调用成员函数:

thread(&bot::execute, this, (char*)commanda.c_str())
                      ^^^^

虽然您确实应该更改功能以采用std::stringconst char*。如果函数尝试修改字符串,或者在线程仍在使用它时销毁commanda,则此处有一个未定义行为的雷区。

lambda可能更具可读性;并且还会通过捕获字符串的副本来修复终身惨败:

thread([=]{execute((char*)commanda.c_str();})