Operating Systems — Lecture 08
$ ./sum_serial
serial sum: 20020000000 expected: 20020000000 OK time: 15 ms
$ ./sum_threads
threads sum: 2960207722 expected: 20020000000 WRONG time: 51 ms
$ ./sum_threads
threads sum: 3332115672 expected: 20020000000 WRONG time: 48 ms
Eight cores lost to one, and could not add. Why? And what does it take to put it right?
Eight threads, 50 million additions each. Additions lost:
| The addition | Every core | One core (taskset -c 0) |
|---|---|---|
| load, add, store | about 80% | typically 14%; from 0 to a third |
| one instruction | about 76% | 0 |
| one locked instruction | 0 | 0 |
$ taskset -c 0 ./count
counter: 343945504 expected: 400000000 lost: 56054496 (14.0%)
involuntary context switches: 101
Map, touch, unmap a page, 50,000 times. Nothing shared in user space.
| Workers | As threads | As processes |
|---|---|---|
| 1 | 108 ms | 92 ms |
| 8 | 1,635 ms | 109 ms |
Where is the shared data?
| Time | Against one thread | |
|---|---|---|
sum_atomic |
255 ms | 17 times |
sum_mutex |
1,215 ms | 80 times |
sum_spinlock |
3,695 ms | 250 times |
$ ./granularity-coarse
value: 10000000 expected: 10000000 time: 3 ms one lock per thread
$ ./granularity-fine
value: 10000000 expected: 10000000 time: 308 ms one lock per addition
A race needs shared data, plus preemption or several cores.
Partition what you can; synchronize what is left.
Keep critical sections few and short, and take locks in one order.
The cheapest lock is the one you did not need.