Creating a thread to a class object

I have the class object Chat *p, and I'm looking to run the method Foo(int num) on it (usually running by p -> Foo(3) for example). I've written this code :

    std::thread F(&Chat::Foo, 4);

though, it does not compile to me, and I also see theres an error, since I was not able to put p -> Foo into it (instead of &Chat::Foo...)

How can I run this code correctly?

Thanks!

Answers


The answer from how object methods actually work. When you call p->foo(3) what the compiler translates it to, roughly speaking, is Chat::foo(p, 3). P is always passed as a hidden parameter in any call to a function. C++ doesn't show you this and you can't actually call Chat::foo(p, 3), this just isn't allowed, but it roughly how things work in reality.

The variable this that is available in any member function is just the address that is passed in as the hidden first parameter and any member variables that you access in the function reference the hidden first parameter. So... what you need to do in order to call any member function as the starting point to a thread, is pass the pointer to the object as it's first parameter. std::thread F(&Chat::Foo, p, 4); will, I believe, start the thread properly.


Need Your Help

three use cases into one use case

uml use-case

I have one actor (admin), he can perform some actions over other user accounts such as creating the account, editing the account and deleting the account account. Should I do something like this:

Update the Style Sheet of a QTextEdit in QThread with pyqt

qt python-2.7 pyqt signals-slots

My GUI is composed of various groups of Qlabels and Qtext, which are updated by it's own QThread that is essentially state machine. My specs require that as the states change, each thread needs to