CS253: Software Development with C++

Spring 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.

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.

Threading

% # How many CPUs?
% lscpu -p | grep -cv '#'
12

Threaded

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

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.

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2019-04-23T13:02

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building