Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a thread inside a class function?

I am very new to C++.

I have a class, and I want to create a thread inside a class's function. And that thread(function) will call and access the class function and variable as well. At the beginning I tried to use Pthread, but only work outside a class, if I want to access the class function/variable I got an out of scope error. I take a look at Boost/thread but it is not desirable because of I don't want to add any other library to my files(for other reason).

I did some research and cannot find any useful answers. Please give some examples to guide me. Thank you so much!

Attempt using pthread(but I dont know how to deal with the situation I stated above):

#include <pthread.h>

void* print(void* data)
{
    std::cout << *((std::string*)data) << "\n";
    return NULL; // We could return data here if we wanted to
}

int main()
{
    std::string message = "Hello, pthreads!";
    pthread_t threadHandle;
    pthread_create(&threadHandle, NULL, &print, &message);
    // Wait for the thread to finish, then exit
    pthread_join(threadHandle, NULL);
    return 0;
}
like image 658
user1701840 Avatar asked Nov 03 '12 02:11

user1701840


1 Answers

You can pass a static member function to a pthread, and an instance of an object as its argument. The idiom goes something like this:

class Parallel
{
private:
    pthread_t thread;

    static void * staticEntryPoint(void * c);
    void entryPoint();

public:
    void start();
};

void Parallel::start()
{
    pthread_create(&thread, NULL, Parallel::staticEntryPoint, this);
}

void * Parallel::staticEntryPoint(void * c)
{
    ((Parallel *) c)->entryPoint();
    return NULL;
}

void Parallel::entryPoint()
{
    // thread body
}

This is a pthread example. You can probably adapt it to use a std::thread without much difficulty.

like image 113
Wug Avatar answered Oct 13 '22 01:10

Wug