CS253: Software Development with C++

Fall 2019

Threads

Show Lecture.Threads as a slide show.

CS253 Threads

pthreads

Simple task

This small program counts the numbers under a billion that are divisible by seventeen, and shows how long that took to run.

int count = 0;
for (int i=1; i<=1e9; i++)
    count += (i % 17 == 0);
cout << count << '\n';
58823529

Real time: 743 ms

Of course it’s a stupid program. The result is ⌊10⁹ ÷ 17⌋ = 58823529.

Threading

// How many CPUs?
cout << thread::hardware_concurrency();
12

How it Usually Works

Threaded

int count_them(int start, int count) {
    int found = 0;
    for (int i=start; i<start+count; i++)
        found += (i % 17 == 0);
    return found;
}

int main() {
    vector<future<int>> counts;
    const auto block = 1e9 / thread::hardware_concurrency();
    for (int b=1; b<=1e9; b+=block)
        counts.emplace_back(async(count_them, b, block));
    int total = 0;
    for (auto &w : counts)
        total += w.get();
    cout << total << '\n';
}
63725489

Real time: 172 ms

Details

Remember to:

Other

We’ve just scratched the surface. Other cool stuff:

<atomic>
integral types which can be safely incremented in threads without problems from a race condition
<mutex>
mutexes, for mutual exclusion, which guard critical sections of code that musn’t run in several threads simutaneously
<condition>
blocking and resuming threads until it’s ok for them to run
<thread>
general thread control: creation, status, killing, joining, etc.