4 ms·
Not all machines reorder instructions, and not all machines have more than one core. You always need control over your compiler, but that often does not suffice
by ncmncm 4y ago
Not all machines reorder instructions, and not all machines have more than one core. You always need control over your compiler, but that often does not suffice.
With more than one core, you cannot do without one of atomics or custom assembly code sequences. And if the CPU reorders instructions all by itself, you need special instructions besides.
Atomics in the language mean you get to let the compiler worry about most things. But an atomic operation may take enormously longer than you hope. An atomic increment may take a hundred times as long as an ordinary increment.
- jstimpfle 4y agoTo clarify, I take atomic aligned reads and writes of machine-sized integers (say 32bit) for granted. I'm not aware of any machines where these simple read and write operations aren't atomic. So I don't consider those "atomics". By "atomics" I understand something like atomic exchange, compare-and-swap, atomic inc/dec. You can implement practical SRSW queues without atomics. Preventing reordering in compiler and CPU is enough. I believe you don't need atomics to achieve mutual exclusion, at least not for 2 processes (Peterson's algorithm). > You always need control over your compiler Yes, this was the other poster's point, you cannot implement threading purely as a library. Function calls like pthread_mutex_lock() must be synchronization points and the compiler must not reorder any instructions around them.