Tread running methode from class

Hello,

I have written a small tcp server class which creates a thread for every new connecting client. This thread runs a client handling methode from the same class.

Using google i made this rule to create the thread:

 
thread(&TCPDataExchanger::clientSender, this, ref(exLib), ref(*newSock), threadId).detach();


My question is why this rule is functioning propperly? Since this rule is executed in a while loop for every new client and the "this" pointer points to the object it self and not to the class to create a new object for every new client? How is it possible the threads don't interferr by using the same object?

MvG Robbert
My question is why this rule is functioning propperly?
I don't know if it does.

Since this rule is executed in a while loop for every new client and the "this" pointer points to the object it self and not to the class to create a new object for every new client?

std::thread creates a new thread of execution.
http://en.cppreference.com/w/cpp/thread/thread

It works on the same instance of the object (because you passed in this as the data pointer). Because of this, access to member data shared between threads must be synchronised by you.

See http://en.cppreference.com/w/cpp/thread

How is it possible the threads don't interferr by using the same object?
That's why you need synchronisation. If you have shared data that isn't synchronised, consider yourself luck so far.
Thanks a lot for your reaction. I made up a little test with a counter where indeed was shown al the threads use the same memory space. So changed my code and make for each thread a new object.

1
2
3
4
5
6
TCPDataExchanger = *clientObject;

while loop{
      clientObject = new TCPDataExchanger;
      thread(&TCPDataExchanger::clientSender, clientObject, ref(exLib), ref(*clientSock), threadId).detach();
}
Last edited on
Topic archived. No new replies allowed.