0

Look at the following snipet:

struct Event
{
    void event1( time_t t );
    void event2( int, int );
}

Event* f = ...;

time_t t; int i1, int i2;

// 1st
std::thread t{ std::bind( &Event::event1, f, std::placeholders::_1 ), t };
std::thread t{ std::bind( &Event::event2, f, std::placeholders::_1, std::placeholders::_2 ), i1, i2 };

// 2nd method
std::thread t{ &Event::event1, f, t };
std::thread t{ &Event::event2, f, i1, i2 };

Which is the difference between 1st and 2nd method. Which method is better?

Stephan Dollberg
  • 32,985
  • 16
  • 81
  • 107
Elvis Dukaj
  • 7,142
  • 12
  • 43
  • 85
  • 1
    `std::bind` is not needed here, for a discussion see the answer in the question I linked. http://stackoverflow.com/a/10673612/893693 – Stephan Dollberg Nov 05 '13 at 14:26

1 Answers1

2

The first method creates a call wrapper around the functions, their Event instances and their respective arguments using std::bind. It then passes these call wrappers to the thread object.

The second method passes the functions, Event instances and arguments directly to the thread objects.

The result of both methods will be the same, although the first method seems to perform an unneccessary step to me.

Use std::bind when you need to pass around a wrapper instead of the individual parameters, e.g:

auto func = std::bind(&Event::event1, f, std::placeholders::_1);

functionTakingCallable(func);
functionTakingCallable2(func);
std::thread t(func, arg);
Felix Glas
  • 15,065
  • 7
  • 53
  • 82