Thread routines can take any number of arguments.
- Variable argument lists—the equivalent of the ellipsis in C—are supported via a new C++ feature called variadic templates.
- That means we have a good amount of flexibility in how we prototype our thread routines
- There's no question this is better than the unsafe void * funkiness that pthreads provides.
- Here's a slightly more involed example where greet threads are configured to say hello a variable number of times. (Online version of the following program can be found right here).
static void greet(size_t id) {
for (size_t i = 0; i < id; i++) {
cout << oslock << "Greeter #" << id << " says 'Hello!'" << endl << osunlock;
struct timespec ts = {
0, random() % 1000000000
};
nanosleep(&ts, NULL);
}
cout << oslock << "Greeter #" << id << " has issued all of his hellos, "
<< "so he goes home!" << endl << osunlock;
}
static const size_t kNumGreeters = 6;
int main(int argc, char *argv[]) {
srandom(time(NULL));
cout << "Welcome to Greetland!" << endl;
thread greeters[kNumGreeters];
for (size_t i = 0; i < kNumGreeters; i++)
greeters[i] = thread(greet, i + 1);
for (thread& greeter: greeters)
greeter.join();
cout << "Everyone's all greeted out!" << endl;
return 0;
}