Show Lecture.Threads as a slide show.
This small program counts the numbers under a billion that are divisible by seventeen, and shows how long that took to run.
timespec beg, end; clock_gettime(CLOCK_MONOTONIC, &beg); int count = 0; for (int i=1; i<=1e9; i++) if (i % 17 == 0) count++; clock_gettime(CLOCK_MONOTONIC, &end); cout << count << '\n' << end.tv_sec - beg.tv_sec + (end.tv_nsec - beg.tv_nsec)/1.0e9;
58823529 0.683625
Of course it’s a stupid program. The result is ⌊10⁹ ÷ 17⌋ = 58823529.
% # How many CPUs? % lscpu -p | grep -cv '#' 12
int count_them(int start, int end) { int count = 0; for (int i=start; i<=end; i++) if (i % 17 == 0) count++; return count; } int main() { vector<future<int>> counts; timespec beg, end; clock_gettime(CLOCK_MONOTONIC, &beg); for (int i=0; i<10; i++) counts.emplace_back(async(count_them, i*1e8+1, (i+1)*1e8)); int total = 0; for (auto &w : counts) total += w.get(); clock_gettime(CLOCK_MONOTONIC, &end); cout << total << '\n' << end.tv_sec - beg.tv_sec + (end.tv_nsec - beg.tv_nsec)/1.0e9; }
58823529 0.148775
Remember to:
#include <future>
for std::future
and std::async
.
g++ -O3 -pthread
to get
optimization and the thread library.
We’ve just scratched the surface. Other cool stuff:
<atomic>
<mutex>
<condition>
<thread>