Reputation: 3776
There are functions for atomic operations for individual bits in Linux, e.g.:
void set_bit( int n, void *addr );
I understand, that, for example if writing a 4-byte number, it can be read by another thread before write completes. But what situation we prevent, when use atomicity for a single bit setting ?
Upvotes: 1
Views: 1624
Reputation: 73181
RAM isn't bit-addressable, so to set just a single bit of a word the CPU has to read the word from RAM, set the bit, then write the word back out to RAM. That's two successive operations (three if we count the OR instruction), so they are not naturally atomic.
As to what situation can be prevented by making the operation atomic, imagine a location in memory currently has value 0. Thread A wants to OR in the second-lowest-bit, and Thread B wants to OR in the lowest-bit. If the operations are atomic, the expected result is that after all is said and done, the word will have its two lowest bits set.
But imagine the two threads' timing is unlucky and things happen in this order...
- Thread A reads the word's value (0x00) from RAM
- Thread B reads the word's value (still 0x00) from RAM
- Thread A computes a new value (0x02) by OR'ing its bit
- Thread B computes a new value (0x01) by OR'ing its bit
- Thread A writes its new value (0x02) to RAM
- Thread B writes its new value (0x01) to RAM
- The word's value in RAM is now 0x01, which isn't what we wanted (we wanted 0x03)
Upvotes: 3