Autumn 2021
Jerry Cain
PDF
class ThreadPool {
public:
ThreadPool(size_t numThreads);
void schedule(const std::function<void(void)>& thunk);
void wait();
~ThreadPool();
};
int main(int argc, char *argv[]) {
ThreadPool pool(4);
for (size_t id = 0; id < 10; id++) {
pool.schedule([id] {
cout << oslock << "Thread (ID: " << id << ") has started." << endl << osunlock;
size_t sleepTime = (id % 3) * 10;
sleep_for(sleepTime);
cout << oslock << "Thread (ID: " << id << ") has finished." << endl << osunlock;
});
}
pool.wait();
cout << "All done!" << endl;
return 0;
}
myth64~$ ./tptest
Thread (ID: 3) has started.
Thread (ID: 2) has started.
Thread (ID: 1) has started.
Thread (ID: 0) has started.
Thread (ID: 3) has finished.
Thread (ID: 4) has started.
Thread (ID: 0) has finished.
Thread (ID: 5) has started.
Thread (ID: 1) has finished.
Thread (ID: 6) has started.
Thread (ID: 4) has finished.
Thread (ID: 7) has started.
Thread (ID: 6) has finished.
Thread (ID: 8) has started.
Thread (ID: 2) has finished.
Thread (ID: 9) has started.
Thread (ID: 9) has finished.
Thread (ID: 5) has finished.
Thread (ID: 7) has finished.
Thread (ID: 8) has finished.
All done!
myth64~$
static void countCS110Processes(int num, const unordered_set<string>& sunetIDs,
map<int, int>& processCountMap, mutex& processCountMapLock) {
int numProcesses = getNumProcesses(num, sunetIDs);
if (numProcesses >= 0) {
processCountMapLock.lock();
processCountMap[num] = numProcesses;
processCountMapLock.unlock();
cout << "myth" << num << " has this many CS110-student processes: "
<< numProcesses << endl;
}
}
static const int kMinMythMachine = 51;
static const int kMaxMythMachine = 66;
static const int kMaxNumThreads = 8;
static void compileCS110ProcessCountMap(const unordered_set<string> sunetIDs,
map<int, int>& processCountMap) {
ThreadPool pool(kMaxNumThreads);
mutex processCountMapLock;
for (int num = kMinMythMachine; num <= kMaxMythMachine; num++) {
pool.schedule([num, &sunetIDs, &processCountMap, &processCountMapLock]() {
countCS110Processes(num, sunetIDs, processCountMap, processCountMapLock);
});
}
pool.wait();
}