0

Please read the complete question before considering this a duplicate.

I have worked on pthread_create() in C which accepts its third argument as "pointer to a function which returns void pointer and takes void pointer as an argument".

i.e., the third argument of pthread_create is void *(*routine)(void *)

So, I just got an idea to use pthread_create() in C++. The function print() which I want to pass to pthread_create() is a member of a class shown below.

Daemon.cpp

#include "Daemon.h"
#include <iostream>
using namespace std;

Daemon::Daemon() {
}

Daemon::~Daemon() {
}

void *Daemon::print(void *args){
    cout << Hello World" << endl;
    return NULL;
}

To take advantage of object oriented design of C++, I put the pthread_create() in a class Thread. This is shown below:

Thread.cpp

#include "Thread.h"
using namespace std;

Thread::Thread( void *(Daemon::*routine)(void *), Daemon& dmObj ) {
    this->thread = 0; //pthread_t thread;
    this->obj = dmObj;// Daemon obj;
    this->functionPointer = routine; // void *(Daemon::*functionPointer)(void *);
}

Thread::~Thread() {

}

int Thread::createThread(){
    //(this->obj.*this->functionPointer)(NULL);
    pthread_create(&this->thread, NULL, (this->obj.*this->functionPointer), NULL);
    return 0;
}

To get above classes working, I called them from main() like shown below:

subsfind.cpp

int main(void) {
    Daemon dm;

    Thread t1( &Daemon::print, dm);
    t1.createThread();
}

If I enable the fourth last line of Thread.cpp, i.e., (this->obj.*this->functionPointer)(NULL);, the output shows as Hello World. This means that, above codes pass pointer to a function just fine. But, I could not pass this function print() (which is a member of a class) to pthread_create(). The compiler error is:

Thread.cpp: In member function ‘int Thread::createThread()’:
Thread.cpp:39:72: error: invalid use of non-static member function
pthread_create(&thread, NULL, (this->obj.*this->functionPointer), NULL);

I am beginner in C++ and I don't know what must I do to get this working. Perhaps I need to cast the object of class Daemon to static or declare print() as static. I tried both of the methods but it didn't work. May be, I am doing it wrong or missing something.

Any idea on this?

Rohit
  • 604
  • 1
  • 10
  • 25

0 Answers0