← All writing

Operating Systems: Three Easy Pieces (2)

Concurrency and Synchronization

Parts: 1 · 2 · 3

26.Concurrency: An Introduction

Perhaps another way to think of this is that eachthread is very much like a separate process, except for one difference: they share the same address space and thus can access the same data.

One other major difference between threads and processes concerns the stack.

Instead of a single stack in the address space, there will be one per thread.

Thetask of transforming your standard single-threaded program into a program that does this sort of work on multiple CPUs is called parallelization, and using a thread per CPU to do this work is a natural and typical way to make programs run faster on modern hardware.

Of course, in either of the cases mentioned above, you could use multiple processes instead of threads.

However, threads share an address space and thus make it easy to share data, and hence are a natural choice when constructing these types of programs. Processes are a more sound choice for logically separate tasks where little sharing of data structures in memory is needed.

28 Locks

28.7 Building Working Spin Locks with Test-And-Set

The simplest bit of hardware support to understand is known as a test-and-set (or atomic exchange) instruction. As it turns out, this slightly more powerful instruction is enough to build a simple spin lock.

28.9 Compare-And-Swap

Another hardware primitive that some systems provide is known as the compare-and-swap instruction (as it is called on SPARC, for example), or compare-and-exchange (as it called on x86).

28.10 Load-Linked and Store-Conditional

Some platforms provide a pair of instructions that work in concert to help build critical sections. On the MIPS architecture [H93], for example, the load-linked and store-conditional instructions can be used in tandem to build locks and other concurrent structures.

28.11 Fetch-And-Add

One final hardware primitive is the fetch-and-add instruction, which atomically increments a value while returning the old value at a particular address.

28.12 Too Much Spinning: What Now?

Thus, any time a thread gets caught spinning in a situation like this, it wastes an entire time slice doing nothing but checking a value that isn’t going to change!

The problem gets worse with NN threads contending for a lock; N−1N − 1 time slices may be wasted in a similar manner, simply spinning and waiting for a single thread to release the lock.

This is a problem for single CPU, if we have multiprocessors as much as threads, spinning problem will mitigate.

28.13 A Simple Approach: Just Yield, Baby

Our first try is a simple and friendly approach: when you are going to spin, instead give up the CPU to another thread.

And this needs help from OS. In this approach, we assume an operating system primitive yield()

which a thread can call when it wants to give up the CPU and let an other thread run.

However this is bad when there are many threads.

28.14 Using Queues: Sleeping Instead Of Spinning

We make thread sleep insteading of spinning, since sleeped thread is in blockd state and it will not get scheduled.

Thus, we must explicitly exert some control over which thread next gets to acquire the lock after the current holder releases it.

29 Lock-based Concurrent Data Structures

When building a concurrent data structure, start with the most basic approach, which is to add a single big lock to provide synchronized access.

30 Condition Variables

Lock is used for mutual exclusion. We need condition variables for synchronization.

30.1 Definition and Routines

A condition variable is an explicit queue that threads can put themselves on when some state of execution (i.e., some condition) is not as desired (by waiting on the condition); some other thread, when it changes said state, can then wake one (or more) of those waiting threads and thus allow them to continue (by signaling on the condition).

To declare such a condition variable, one simply writes something like this: pthread cond t c;, which declares c as a condition variable (note: proper initialization is also required). A condition variable has two operations associated with it: wait() and signal(). The wait() call is executed when a thread wishes to put itself to sleep; the signal() call s executed when a thread has changed something in the program and thus wants to wake a sleeping thread waiting on this condition.

c
pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m);
pthread_cond_signal(pthread_cond_t *c);

We will often refer to these as wait() and signal() for simplicity. One thing you might notice about the wait() call is that it also takes a mutex as a parameter; it assumes that this mutex is locked when wait() is called. The responsibility of wait() is to release the lock and put the calling thread to sleep (atomically); when the thread wakes up (after some other thread has signaled it), it must re-acquire the lock before returning to the caller.

30.2 The Producer/Consumer (Bounded Buffer) Problem

example:

c
1 int buffer[MAX];
2 int fill_ptr = 0;
3 int use_ptr = 0;
4 int count = 0;
5
6 void put(int value) {
7 buffer[fill_ptr] = value;
8 fill_ptr = (fill_ptr + 1) % MAX;
9 count++;
10 }
11
12 int get() {
13 int tmp = buffer[use_ptr];
14 use_ptr = (use_ptr + 1) % MAX;
15 count--;
16 return tmp;
17 }

c
1 cond_t empty, fill;
2 mutex_t mutex;
3
4 void *producer(void *arg) {
5 int i;
6 for (i = 0; i < loops; i++) {
7 Pthread_mutex_lock(&mutex); // p1
8 while (count == MAX) // p2
9 Pthread_cond_wait(&empty, &mutex); // p3
10 put(i); // p4
11 Pthread_cond_signal(&fill); // p5
12 Pthread_mutex_unlock(&mutex); // p6
13 }
14 }
15
16 void *consumer(void *arg) {
17 int i;
18 for (i = 0; i < loops; i++) {
19 Pthread_mutex_lock(&mutex); // c1
20 while (count == 0) // c2
21 Pthread_cond_wait(&fill, &mutex); // c3
22 int tmp = get(); // c4
23 Pthread_cond_signal(&empty); // c5
24 Pthread_mutex_unlock(&mutex); // c6
25 printf("%d\n", tmp);
26 }
27 }

n the code, producer threads wait on the condition empty, and signals fill. Conversely, consumer threads wait on fill and signal empty. By doing so, the second problem above is avoided by design: a consumer can never accidentally wake a consumer, and a producer can never accidentally wake a producer.

31 Semaphores

Indeed, Dijkstra and colleagues invented the semaphore as a single primitive for all things related to synchronization; as you will see, one can use semaphores as both locks and condition variables.

TIP: BE CAREFUL WITH GENERALIZATION

One could view semaphores as a generalization of locks and condition variables; however, is such a generalization needed? And, given the difficulty of realizing a condition variable on top of a semaphore, perhaps this generalization is not as general as you might think.

32 Common Concurrency Problems

We now dive into these different classes of bugs (non-deadlock, deadlock) a bit more deeply.

32.2 Non-Deadlock Bugs

We now discuss the two major types of nondeadlock bugs found by Lu et al.: atomicity violation bugs and order violation bugs.

32.3 Deadlock Bugs

Learned many times.

33 Event-based Concurrency

To be learned.


← Previous · Next →

← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.