Martin Dvoracek
Martin Dvoracek

Reputation: 1738

Function for the thread within a class in C++

I'm having troubles with creation of the function, that should handle new thread. When I create it outside of the class, everything works allright, but when I want to create it inside a class, I can't realize, how to call it.

I call the function with:

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

and the function itself looks like this:

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);
    }
}

but when I declare it within a class e.g. void * Client::sendMessage(void *threadid) , I can't even build it because I get main.cpp:90:37: error: argument of type ‘void* (Client::)(void*)’ does not match ‘void* (*)(void*)’ Does anybody have any idea, what can cause it and how to fix it?

Upvotes: 2

Views: 1575

Answers (1)

sehe
sehe

Reputation: 392833

Just a quick demonstration of how std::thread can quickly make all your woes disappear (by seemlessly integrating with std::bind style invocation):

#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();
}

Upvotes: 4

Related Questions