# Atomicity and semaphores

*update Oct 22, 2017 15:19*

## Kinds of atomicity

**synthetic (voluntary) atomicity**: programs and/or threads obey locking to avoid operating at the same time.\
**kernel atomicity**: when a system call is executing, the scheduler won't interrupt it.\
**instruction atomicity**: some machine instructions preclude concurrent operations.\
**special-purpose system calls**: some specific system calls execute program instructions in an atomic (uninterruptible) fashion.

## Kinds of locks

**Between threads: mutexes**\
user mode (except when they block!)\
exploit shared memory\
binary: locked or unlocked

**Between threads: unnamed semaphores**\
user mode (except when they block!)\
exploit shared memory\
they're integers\
Unlimited numbers available.

**Between processes: named semaphores**\
kernel mode: live in kernel memory.\
no shared memory.\
They're integers. An array offset in a kernel table.\
Limited number available.

**Between machines: network semaphores**\
network objects\
use network communications\
no shared architecture.

## What is a mutex

Basically, one word of **user** memory.\
Utilize a simple race condition to acquire lock, based upon **atomicity of operations in assembly language**. If the word of memory is > 0, then a lock has been acquired.\
If the word of memory == 0, then there is no lock.\
Testset: **if word==0 then word=1** as an **atomic operation**.

## what is a semaphore

A semaphore is an integer to which access is atomic.\
Initialized to some integer value.\
locks decrement it.\
unlocks increment it.\
value determines number of concurrent locks available.

## Mutex versus semphores

![](https://1028698231-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LDKV99X0zUwOwNL3Gby%2F-LDNGwyCL8pFNM4OL7D0%2F-LDNH6i2wXVKxGYEwNLA%2FScreen%20Shot%202017-10-22%20at%204.15.51%20PM.png?generation=1527268287274410\&alt=media)

* Mutexes can only be locked or unlocked, they are sometimes called "binary semaphores".
* Semaphores have an integer value that is the number of locks available. Can read a semaphore's value via sem\_getvalue(\&sem,\&val) where val is an int.&#x20;

## Using a semphore

![](https://1028698231-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LDKV99X0zUwOwNL3Gby%2F-LDNGwyCL8pFNM4OL7D0%2F-LDNH6i7cKFJ4cEpxyt0%2FScreen%20Shot%202017-10-22%20at%204.38.38%20PM.png?generation=1527268335004093\&alt=media)
