C++ provides threading and synchronization directives as part of the language now.
- Here's the introverts example we've seen before—this time in C++! (Full version of this program is online here).
#include <iostream> // for cout, endl
#include <thread> // for C++ thread support
#include "ostreamlock.h" // for CS110 iomanipulators (oslock, osunlock) used to lock down streams
using namespace std;
static void recharge() {
cout << oslock << "I recharge by spending time alone." << endl << osunlock;
}
static const size_t kNumIntroverts = 6;
int main(int argc, char *argv[]) {
cout << "Let's hear from " << kNumIntroverts << " introverts." << endl
thread introverts[kNumIntroverts]; // declare array of empty thread handles
for (thread& introvert: introverts)
introvert = thread(recharge); // move anonymous threads into empty handles
for (thread& introvert: introverts)
introvert.join();
cout << "Everyone's recharged!" << endl;
return 0;
}