Threading with Initialized Class Member Function

Hello everyone,

I'm quite new to threading and I was wondering why my below code doesn't work..

1
2
3
4
5
    serverBEGIN server1;
    serverBEGIN server2;

    std::thread (server1.startServer, "192.168.255.1", "9999").detach();
    std::thread (server2.startServer, "192.168.111.1", "9999").detach();



Here is the definition for the startServer function:
 
int serverBEGIN::startServer (const char addrIP[16], const char numPORT[6]);


I tried putting "&" in front of the server1/2 member functions in the arugment for std::thread and I tried putting *this and this between the member function and the addrIP but no luck...

Any help would be appreciated!

Thank you everyone! :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
serverBEGIN server1;
serverBEGIN server2;

const auto fn = &serverBEGIN::startServer ; // pointer to member

// pass by value - threads operate on copies of server1 and server2
// objects server1 and server2 are not accessed by the threads
std::thread ( fn, server1, "192.168.255.1", "9999" ).detach();
std::thread ( fn, server2, "192.168.111.1", "9999" ).detach();

// pass by (wrapped) reference - threads operate on objects server1 and server2
// note: dangerous to detach the threads; if these objects are destroyed before
// the threads have finished accessing them, there will be undefined behaviour
std::thread ( fn, std::ref(server1), "192.168.255.1", "9999" ).detach();
std::thread ( fn, std::ref(server2), "192.168.111.1", "9999" ).detach();

// pass pointer by value - threads operate on objects server1 and server2
// note: dangerous to detach the threads; if these objects are destroyed before
// the threads have finished accessing them, there will be undefined behaviour
std::thread ( fn, std::addressof(server1), "192.168.255.1", "9999" ).detach();
std::thread ( fn, std::addressof(server2), "192.168.111.1", "9999" ).detach();

// EDIT: added
// if serverBEGIN is a moveable type: move the objects to the threads
// objects server1 and server2 should not used locally after this
std::thread ( fn, std::move(server1), "192.168.255.1", "9999" ).detach();
std::thread ( fn, std::move(server2), "192.168.111.1", "9999" ).detach();
Last edited on
Awesome! thank you for the code :)

Just out of curiosity, what is the main difference between ref and addressof.. if there is any.


Thank you.
std::ref() returns a wrapped reference - a std::reference_wrapper<>
http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper

std::addressof() returns a pointer - the actual address of the object.
http://en.cppreference.com/w/cpp/memory/addressof

The constructor of the thread accepts either.
See 3) in: http://en.cppreference.com/w/cpp/thread/thread/thread
Topic archived. No new replies allowed.