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();
|