boost::thread doesn't like meshing with OO

Hi, I'm pretty new to OO and threading, and am using boost::thread for multithreading my program.

My issue stems from not understanding how to launch a new thread for a function within a class. That makes no sense now that I read it back to myself, so let me just post my code.


1
2
3
4
5
6
7
8
9
10
11
class somethingWithThreads{
public: 
     void aFunction();
private:
     void internalFunction(int arg);
};

void somethingWithThreads::aFunction(){
    //fun code things here
    boost::thread workerThread(internalFunction, 5); //where 5 is the arg
}



apparently this isn't the correct syntax for creating a thread pointing at a class function. Originally I thought the issue was with the internalfunction being private, but changing it to public didn't change the issue. I've tried all kinds of syntaxes for how to pass the internalFunction to the boost, including somethingWithThreads::internalFunction
&somethingWithThreads::internalFunction
etc.

It would probably be an understatement to say I don't know what I'm doing with classes, but all my professors say that I should be writing my c++ code more OO-oriented than function-oriented, so I'm stuck in a pickle of learning OO the hard way.

Thanks for your time.
Last edited on
Internal function needs to have a somethingWithThreads class passed to it as well (as the first argument). Otherwise it wouldn't know what the this pointer should be pointing at.
Yeah, I tried doing boost::thread workerThread(somethingWithThreads::internalFunction, 5),
but I get a compiler error that:

function call missing argument list; use '&somethingWithThreads::internalFunction' to create a pointer to member

So then I tried using its suggestion and I got a compiler error that:

error C2064: term does not evaluate to a function taking 2 arguments class does not define an 'operator()' or a user defined conversion operator to a pointer-to-function or reference-to-function that takes appropriate number of arguments

I realize that it says 2 arguments there, my actual internalFunction in my code has 2 args instead of one in the example.
I believe it was
 
boost::thread workerThread(&somethingWithThreads::internalFunction,this,5);
oh my god that worked, you're my hero.

just out of curiosity, why does the this keyword need to be included as the second arg?
Because it's a parameter to the function. Without it, boost::thread can't know which somethingWithThreads object you're calling internalFunction() on.
Topic archived. No new replies allowed.