0

I want to start a struct method in an own thread:

g_thread_new( "NewThread", mymethod , NULL)

The problem is, the program only compiles if I set the method to "static":

static gpointer mymethod(gpointer nrp) { puts(this->mystring) ; ... }

But if I set the method to "static" I cannot access the struct instance variables like this->mystring.

Is there a way to use g_thread_new with class methods AND access instance variables?

Kenobi
  • 425
  • 1
  • 4
  • 19
  • possible duplicate of [pthread Function from a Class](http://stackoverflow.com/questions/1151582/pthread-function-from-a-class) – user1708860 Sep 15 '13 at 22:41
  • Which instance's variables are you expecting to access? You haven't selected an instance. – David Schwartz Sep 15 '13 at 22:43
  • What's going on, we literally had the same question [five minutes ago](http://stackoverflow.com/q/18818156/596781)? – Kerrek SB Sep 15 '13 at 22:43
  • Hello @DavidSchwartz, you mean I could handle a kind of a pointer with the thread pointing to the instance that I want to deal with? Can I then overwrite the this-> - field? – Kenobi Sep 19 '13 at 18:44
  • 1
    @Kenobi Exactly. You pass a pointer to the instance to the thread and then the thread can invoke a member function on that instance, causing the member function's `this` pointer to point to the correct instance. – David Schwartz Sep 19 '13 at 18:46

1 Answers1

0

What you can and should do is receive a void* in your static function as a parameter from the thread. That void* is the object that you want it's function called. Just cast it to the object's type and call the method.

Also, consider using boost::thread.

user1708860
  • 1,683
  • 13
  • 32
  • That sounds promising... I now use a workaround for that problem, but I'll consider your answer when I finally throw out the workaround. One question - will this void* object help me access class variables or will it prevent me to having to put the method to static? – Kenobi Sep 19 '13 at 18:40