Sei sulla pagina 1di 8

Concurrency: An Introduction

Operating System: Three Easy Pieces

Youjip Won 1

 A new abstraction for a single running process

 Multi-threaded program
 A multi-threaded program has more than one point of execution.

 Multiple PCs (Program Counter)

 They share the same address space.

Youjip Won 2
Context switch between threads

 Each thread has its own program counter and set of registers.
 One or more thread control blocks(TCBs) are needed to store the state
of each thread.

 When switching from running one (T1) to running the other (T2),
 The register state of T1 be saved.

 The register state of T2 restored.

 The address space remains the same.

Youjip Won 3
The stack of the relevant thread

 There will be one stack per thread.

0KB The code segment: 0KB

Program Code where instructions live Program Code
The heap segment:
Heap Heap
contains malloc’d data
2KB dynamic data structures 2KB
(it grows downward)



Stack (2)
(it grows upward)
The stack segment: (free)
15KB contains local variables 15KB
Stack (1) arguments to routines, Stack (1)
16KB return values, etc. 16KB
A Single-Threaded Two threaded
Address Space Address Space

Youjip Won 4
Race condition

 Example with two threads(A race condition is an undesirable situation that occurs when two or more process can
access and change the shared data at the same time )

 counter = counter + 1 (default is 50)

 We expect the result is 52. However,

(after instruction)
OS Thread1 Thread2 PC %eax counter
before critical section 100 0 50
mov 0x8049a1c, %eax 105 50 50
add $0x1, %eax 108 51 50

save T1’s state
restore T2’s state 100 0 50
mov 0x8049a1c, %eax 105 50 50
add $0x1, %eax 108 51 50
mov %eax, 0x8049a1c 113 51 51
save T2’s state
restore T1’s state 108 51 50
mov %eax, 0x8049a1c 113 51 51

Youjip Won 5
Critical section

 (In concurrent programming, concurrent accesses to shared resources

can lead to unexpected or erroneous behavior, so parts of the progra
m where the shared resource is accessed are protected. This protected
section is the critical section or critical region)

Youjip Won 6
Critical section

 A piece of code that accesses a shared variable and must not be

concurrently executed by more than one thread.
 Multiple threads executing critical section can result in a race condition.

 Need to support atomicity for critical sections (mutual exclusion)

 (A mutual exclusion (mutex) is a program object that prevents simultaneo

us access to a shared resource. This concept is used in concurrent progra
mming with a critical section, a piece of code in which processes or thread
s access a shared resource.)

Youjip Won 7

 Ensure that any such critical section executes as if it were a single

atomic instruction (execute a series of instructions atomically).

1 lock_t mutex;
2 . . .
3 lock(&mutex);
4 balance = balance + 1; Critical section
5 unlock(&mutex);

Youjip Won 8