Previous | Next --- Slide 16 of 65
Back to Lecture Thumbnails
haoala

There is a semantic difference between this code and one where the atomic is replaced by a lock and unlock at the start and end of the code block respectively.

atomic is declarative, it just says that instructions in it need to be atomic. The semantics say nothing about how it should be implemented.

Using locks, we are telling the system that we want to take a lock and unlock it. We have achieved mutual exclusion, but those are not the semantics of lock and unlock.

panda

The semantics of this program are that you are abstracting it-- by using atomic(), the program will know that it is atomic and we know it is implemented atomically, in whatever way, and we are guaranteed it's correct. We don't know how it is implemented and we don't need to know how it is implemented either, we just know it is atomic (hence the abstraction) so it could be implemented in parallel or sequentially also.

On the other hand if you used lock() and unlock() instead of atomic(), we are not specifically telling the program that we are making it atomic-- we are simply taking a lock, and as programmers we know we are making a mutual exclusion (and potentially incorrectly too).

o_o

So, the difference between using a lock and using atomic is that a lock is an imperative abstraction whereas atomic is a declarative abstraction. Thus, it depends on the underlying implementation and overhead of atomic to see if it performs better or worse than using a lock. In what circumstances is using atomic better than using a lock?