C++ 中构造函数中的线程

Threads in Constructor in C++

本文关键字:线程 构造函数 C++      更新时间:2023-10-16

我正在尝试在一个类的构造函数中创建线程,该函数将在该类中运行几个函数,我已经尝试过:

ServerLogic::ServerLogic(SOCKET sock)
{
    this->sock = sock;
    this->dispatchThread = new std::thread(this->dispatchMessage);
}
void ServerLogic::dispatchMessage(){
    /*
    *   this function will handle the connetions with the clients
    */
    char recievedMsg[1024];
    int connectResult;
    //receive data
    while (true){
        connectResult = recv(this->sock, recievedMsg, sizeof(recievedMsg), 0);
        //in case everything good send to diagnose
        if (connectResult != SOCKET_ERROR){
            this->messagesToDiagnose.push(std::string(recievedMsg));
        }
        else{
            /*
            *   destructor
            */
        }
    }
}

但它给了我一个错误:'ServerLogic::d ispatchMessage':函数调用缺少参数列表;使用"&ServerLogic::d ispatchMessage"创建指向成员的指针。

IntelliSense:函数"std::thread::thread(

const std::thread &)"(在"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\thread")的第70行声明)无法引用 - 它是一个已删除的函数。

我认为错误消息基本上是在告诉您该怎么做。 考虑以下代码(这是有问题的,但只是为了说明这一点):

#include <thread>
class foo
{
public:
    foo()
    {
        std::thread(&foo::bar, this);
    }
    void bar()
    {
    }
};

int main()
{
    foo f;
}

若要指定成员函数,请使用

std::thread(&foo::bar, this);