函数用于c++中类中的线程

Function for the thread within a class in C++

本文关键字:线程 函数 c++ 用于      更新时间:2023-10-16

我在创建函数时遇到了麻烦,应该处理新线程。当我在类外创建它时,一切正常,但当我想在类内创建它时,我不知道如何调用它。

我调用函数:

pthread_t thread;
pthread_create(&thread, NULL,
        sendMessage, (void *) fd);

和函数本身是这样的:

void * sendMessage(void *threadid) {
    string message;
    const char * c;
    char buffer[200];
    int fd = (long) threadid;
    while (true) {
        cin >> message;
        if (message == "exit") {
            break;
        }
        c = message.c_str();
        strncpy(buffer, c, sizeof ( buffer));
        send(fd, buffer, strlen(buffer), 0);
    }
}

但是当我在一个类中声明它时,例如void * Client::sendMessage(void *threadid),我甚至不能构建它,因为我得到main.cpp:90:37: error: argument of type ‘void* (Client::)(void*)’ does not match ‘void* (*)(void*)’。有没有人知道,什么会导致它以及如何修复它?

只是std::thread如何快速使您的所有问题消失的快速演示(通过无缝集成std::bind样式调用):

#include <string>
#include <thread>
#include <memory>
void some_function(int i, std::string bla) 
{ 
}
struct some_class
{
    void some_member_function(double x) const
    {
    }
};
int main()
{
    std::thread t1(&some_function, 42, "the answer");
    std::thread t2;
    {
        some_class instance;
        t2 = std::thread(&some_class::some_member_function, 
                std::ref(instance), 
                3.14159);
        t2.join(); // need to join before `instance` goes out of scope
    }
    {
        auto managed = std::make_shared<some_class>();
        t2 = std::thread([managed]() 
                { 
                    managed->some_member_function(3.14159); 
                });
        // `managed` lives on 
    }
    if (t1.joinable()) t1.join();
    if (t2.joinable()) t2.join();
}