SlideShare a Scribd company logo
1 of 33
Download to read offline
Concurrency
Beuth Hochschule

Summer Term 2014

!
Pictures (C) W. Stallings, if not stated otherwise

Pthread material from http://computing.llnl.gov/tutorials/pthreads

!
!
„When two trains approach each other at a crossing, 

both shall come to a full stop and neither shall start up again 

until the other has gone.“

[Kansas legislature, early 20th century]"
2
Whathappens?
ParProg | Introduction PT / FF 14
Abstraction of Concurrency [Breshears]
• Processes / threads represent the execution of atomic statements
• „Atomic“ can be defined on different granularity levels, e.g. source code line,

so concurrency should be treated as abstract concept
• Concurrent execution is the interleaving of atomic statements from multiple
sequential processes

• Unpredictable execution sequence of atomic instructions due to non-deterministic
scheduling and dispatching, interrupts, and other activities

• Concurrent algorithm should maintain properties for all possible inter-leavings

• Example: All atomic statements are eventually included (fairness)

• Some literature distinguishes between interleaving (uniprocessor) and 

overlapping (multiprocessor) of statements - same problem
3
ParProg | Introduction PT / FF 14
Concurrency
• Management of concurrent activities in an
operating system

• Multiple applications in progress at the
same time, non-sequential operating
system activities

• Time sharing for interleaved execution

• Demands dispatching and
synchronization

• Parallelism: Actions are executed
simultaneously
• Demands parallel hardware 

• Relies on a concurrent application
4
Core
Core
time
Thread1
Thread2
Thread1
Thread2
Memory Memory
Core
ParProg | Introduction PT / FF 14
Concurrency is Hard
• Sharing of global resources

• Concurrent reads and writes on the same variable makes order critical

• Optimal management of resource allocation

• Process gets control over a I/O channel and is then suspended before using it

• Programming errors become non-deterministic

• Order of interleaving may / may not activate the bug

• Happens all with concurrent execution, which means even on uniprocessors

• Race condition

• The final result of an operation depends on the order of execution

• Well-known issue since the 60‘s, identified by E. Dijkstra
5
ParProg | Introduction PT / FF 14
Race Condition
• Executed by two threads on uniprocessor

• Executed by two threads on multiprocessor

• What happens ?
6
void echo() {
char_in = getchar();
char_out = char_in;
putchar(char_out);
}
This is a
„critical
section“
ParProg | Introduction PT / FF 14
Terminology
• Deadlock („Verklemmung“)
• Two or more processes / threads are unable to proceed

• Each is waiting for one of the others to do something

• Livelock
• Two or more processes / threads continuously change their states in response to
changes in the other processes / threads 

• No global progress for the application

• Race condition
• Two or more processes / threads are executed concurrently

• Final result of the application depends on the relative timing of their execution
7
ParProg | Introduction PT / FF 14
Potential Deadlock
8
I need quad
A and B
I need quad
B and C
I need quad
C and B
I need quad
D and A
ParProg | Introduction PT / FF 14
Actual Deadlock
9
HALT until
B is free
HALT until
C is free
HALT until
D is free
HALT until
A is free
ParProg | Introduction PT / FF 14
Terminology
• Starvation („Verhungern“)
• A runnable process / thread is overlooked indefinitely

• Although it is able to proceed, it is never chosen to run (dispatching / scheduling)

• Atomic Operation („Atomare Operation“)
• Function or action implemented as a sequence of one or more instructions

• Appears to be indivisible - no other process / thread can see an intermediate state
or interrupt the operation

• Executed as a group, or not executed at all

• Mutual Exclusion („Gegenseitiger Ausschluss“)
• The requirement that when one process / thread is using a resource, 

no other shall be allowed to do that
10
ParProg | Introduction PT / FF 1411
Example: The Dining Philosophers (E.W.Dijkstra)
• Five philosophers work in a college, each philosopher has a room for thinking

• Common dining room, furnished with a circular table, 

surrounded by five labeled chairs

• In the center stood a large bowl of spaghetti, which was constantly replenished

• When a philosopher gets hungry:

• Sits on his chair

• Picks up his own fork on the left and plunges

it in the spaghetti, then picks up the right fork

• When finished he put down both forks 

and gets up 

• May wait for the availability of the second fork
ParProg | Introduction PT / FF 14
Example: The Dining Philosophers (E.W.Dijkstra)
• Idea: Shared memory synchronization has different standard issues

• Explanation of deadly embrace (deadlock) and starvation (livelock)
• Forks taken one after the other, released together

• No two neighbors may eat at the same time

• Philosophers as tasks, forks as shared resource

• How can a deadlock happen ?

• All pick the left fork first and wait for the right

• How can a live-lock (starvation) happen ?

• Two fast eaters, sitting in front of each other

• One possibility: Waiter solution (central arbitration)
12
(C)Wikipedia
ParProg | Introduction PT / FF 14
Critical Section
• n threads all competing to use a shared resource (i.e.; shared data, spaghetti forks)

• Each thread has some code - critical section - in which the shared data is accessed

• Mutual Exclusion demand
• Only one thread at a time is allowed into its critical section, among all threads that
have critical sections for the same resource.

• Progress demand
• If no other thread is in the critical section, the decision for entering should not be
postponed indefinitely. Only threads that wait for entering the critical section are
allowed to participate in decisions. (deadlock problem)

• Bounded Waiting demand
• It must not be possible for a thread requiring access to a critical section to be
delayed indefinitely by other threads entering the section. (starvation problem)
13
ParProg | Introduction PT / FF 14
Critical Section
• Only 2 threads, T0 and T1

• General structure of thread Ti (other thread Tj)

• Threads may share some common variables to synchronize their actions
14
do {
enter section
critical section
exit section
reminder section
} while (1);
ParProg | Introduction PT / FF 14
Critical Section Protection with Hardware
• Traditional solution was interrupt disabling, but works only on multiprocessor

• Concurrent threads cannot overlap on one CPU

• Thread will run until performing a system call or interrupt happens

• Software-based algorithms also do not work, due to missing atomic statements

• Modern architectures need hardware support with atomic machine instructions

• Test and Set instruction - 

read & write memory at once

• If not available, atomic swap 

instruction is enough

• Busy waiting, starvation or 

deadlock are still possible
15
#define LOCKED 1!
int TestAndSet(int* lockPtr) {!
int oldValue;!
oldValue = SwapAtomic(lockPtr, LOCKED);!
return oldValue;!
}
function Lock(int *lock) {!
while (TestAndSet (lock) == LOCKED);!
}
16
„Manual“ implementation!
of a critical section for !
interleaved output
ParProg | Introduction PT / FF 14
Binary and General Semaphores [Dijkstra]
• Find a solution to allow waiting processes 

to ,sleep‘

• Special purpose integer called semaphore

• P-operation: Decrease value of its argument 

semaphore by 1 as atomic step

• Blocks if the semaphore is already zero -

wait operation

• V-operation: Increase value of its argument 

semaphore by 1 as atomic step

• Releases one instance of the resource 

for other processes - signal operation

• Solution for critical section shared between N processes

• Binary semaphore has initial value of 1, counting semaphore of N
17
wait (S):
while (S <= 0);
S--; // atomic
signal (S):
S++; // atomic
do {
wait(mutex);
critical section
signal(mutex);

remainder section
} while (1);
ParProg | Introduction PT / FF 14
Semaphores and Busy Wait
• Semaphores may suspend/resume threads to avoid busy waiting

• On wait operation 

• Decrease value

• When value <= 0, calling thread is suspended and added to waiting list

• Value may become negative with multiple waiters

• On signal operation

• Increase value

• When value <= 0, one waiting thread is

woken up and remove from the waiting list
18
typedef struct {
int value;
struct thread *L;
} semaphore;
ParProg | Introduction PT / FF 14
Shared Data Protection by Semaphores
19
ParProg | Introduction PT / FF 14
POSIX Pthreads
• Part of the POSIX specification collection, defining an API for thread creation and
management (pthread.h)

• Implemented by all (!) Unix-alike operating systems available

• Utilization of kernel- or user-mode threads depends on implementation

• Groups of functionality (pthread_ function prefix)

• Thread management - Start, wait for termination, ...

• Mutex-based synchronization

• Synchronization based on condition variables
• Synchronization based on read/write locks and barriers
• Semaphore API is a separate POSIX specification (sem_ prefix)
20
ParProg | Introduction PT / FF 14
POSIX Pthreads
21
ParProg | Introduction PT / FF 14
POSIX Pthreads
22
• pthread_create()
• Create new thread in the process, with given routine and argument

• pthread_exit(), pthread_cancel()
• Terminate thread from inside our outside of the thread

• pthread_attr_init() , pthread_attr_destroy()
• Abstract functions to deal with implementation-specific attributes

(f.e. stack size limit)

• See discussion in man page about how this improves portability
int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void *),
void *restrict arg);
23
/******************************************************************************!
* FILE: hello.c!
* DESCRIPTION:!
* A "hello world" Pthreads program. Demonstrates thread creation and!
* termination.!
* AUTHOR: Blaise Barney!
* LAST REVISED: 08/09/11!
******************************************************************************/!
#include <pthread.h>!
#include <stdio.h>!
#include <stdlib.h>!
#define NUM_THREADS! 5!
!
void *PrintHello(void *threadid)!
{!
long tid;!
tid = (long)threadid;!
printf("Hello World! It's me, thread #%ld!n", tid);!
pthread_exit(NULL);!
}!
!
int main(int argc, char *argv[])!
{!
pthread_t threads[NUM_THREADS];!
int rc;!
long t;!
for(t=0;t<NUM_THREADS;t++){!
printf("In main: creating thread %ldn", t);!
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);!
if (rc){!
printf("ERROR; return code from pthread_create() is %dn", rc);!
exit(-1);!
}!
}!
!
/* Last thing that main() should do */!
pthread_exit(NULL);!
}
ParProg | Introduction PT / FF 14
POSIX Pthreads
24
• pthread_join()
• Blocks the caller until the specific thread terminates

• If thread gave exit code to pthread_exit(), it can be determined here

• Only one joining thread per target is thread is allowed

• By the book, threads should be joinable (old implementations problem)

• pthread_detach()
• Mark thread as not-joinable (detached) - may free some system resources

• pthread_attr_setdetachstate()
• Prepare attr block so that a thread can be created in some detach state
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
ParProg | Introduction PT / FF 14
POSIX Pthreads
25
26
/*****************************************************************************!
* FILE: join.c!
* AUTHOR: 8/98 Blaise Barney!
* LAST REVISED: 01/30/09!
******************************************************************************/!
#include <pthread.h>!
#include <stdio.h>!
#include <stdlib.h>!
#define NUM_THREADS! 4!
!
void *BusyWork(void *t) {!
int i;!
long tid;!
double result=0.0;!
tid = (long)t;!
printf("Thread %ld starting...n",tid);!
for (i=0; i<1000000; i++) {!
result = result + sin(i) * tan(i); }!
printf("Thread %ld done. Result = %en",tid, result);!
pthread_exit((void*) t); }!
!
int main (int argc, char *argv[]) {!
pthread_t thread[NUM_THREADS];!
pthread_attr_t attr;!
int rc; long t; void *status;!
!
pthread_attr_init(&attr);!
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);!
!
for(t=0; t<NUM_THREADS; t++) {!
printf("Main: creating thread %ldn", t);!
rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t); !
if (rc) {!
printf("ERROR; return code from pthread_create() is %dn", rc);!
exit(-1);}}!
!
pthread_attr_destroy(&attr);!
for(t=0; t<NUM_THREADS; t++) {!
rc = pthread_join(thread[t], &status);!
if (rc) {!
printf("ERROR; return code from pthread_join() is %dn", rc);!
exit(-1); }!
printf("Main: completed join with thread %ld having a status of %ldn",t,(long)status);}!
!
printf("Main: program completed. Exiting.n");!
pthread_exit(NULL); }
ParProg | Introduction PT / FF 14
POSIX Pthreads
27
• pthread_mutex_init()
• Initialize new mutex, which is unlocked by default

• pthread_mutex_lock(), pthread_mutex_trylock()
• Blocking / non-blocking wait for a mutex lock

• pthread_mutex_unlock()
• Operating system scheduling decides about wake-up preference

• Focus on speed of operation, no deadlock or starvation protection mechanism
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
ParProg | Introduction PT / FF 14
Windows vs. POSIX Synchronization
28
Windows POSIX
WaitForSingleObject pthread_mutex_lock()
WaitForSingleObject(timeout==0) pthread_mutex_trylock()
Auto-reset events Condition variables
ParProg | Introduction PT / FF 14
Spinlocks
29
Processor'B'Processor'A'
do#
####acquire_spinlock(DPC)#
un6l#(SUCCESS)#
#
begin#
####remove#DPC#from#queue#
end#
#
release_spinlock(DPC)#
do#
####acquire_spinlock(DPC)#
un6l#(SUCCESS)#
#
begin#
####remove#DPC#from#queue#
end#
#
release_spinlock(DPC)#
.#
.#
.#
.#
.#
.#
Cri6cal#sec6on#
spinlock#
DPC# DPC#
ParProg | Introduction PT / FF 14
Spinlocks
30
Try$to$acquire$spinlock:$
Test,$set,$was$set,$loop$
Test,$set,$was$set,$loop$
Test,$set,$was$set,$loop$
Test,$set,$was$set,$loop$
Test,$set,$WAS$CLEAR$
(got$the$spinlock!)$
Begin$updaCng$data$
Try$to$acquire$spinlock:$
Test,$set,$WAS$CLEAR$
(got$the$spinlock!)$
Begin$updaCng$data$
$that’s$protected$by$the$
$spinlock$
$
$
(done$with$update)$
Release$the$spinlock:$
Clear$the$spinlock$bit$
$
CPU$1$ CPU$2$
ParProg | Introduction PT / FF 14
Windows: Queued Spinlocks
• Problem: Checking status of spinlock via test-and-set creates bus contention
• Idea of queued spinlocks:

• Each spinlock maintain a queue of waiting processors

• First processor acquires the lock directly

• Other processors are added to the queue and spin on a local wait bit

• On release, the according processor resets the wait bit of the next CPU in queue

• Exactly one processor is being signaled

• Pre-determined wait order

• Result: Busy-wait loops of all CPUs require 

no access to main memory

• (Check reading list for details)
31
ParProg | Introduction PT / FF 14
Linux: Spinlocks
• Common critical section strategy in the Linux kernel

• Uniprocessor system with disabled kernel preemption:

• Kernel threads are never interrupted, so locks are deleted at compile time

• Uniprocessor system with enabled kernel preemption:

• Spinlock code is replaced with disabling / enabling of interrupts

• Multiprocessor system

• Spinlock code compiled into monolithic kernel

• Additional support for reader-writer spinlocks, which favor the reader

• Similar API for portability
32
ParProg | Introduction PT / FF 14
Linux: Spinlocks
33
• void spin_lock_init(spinlock_t *lock): 

Initializes given spinlock
• void spin_lock(spinlock_t *lock): 

Acquires the specified lock, spinning if needed until it is available

• void spin_lock_irq(spinlock_t *lock): 

Like spin_lock(), but also disables interrupts on the local processor

• Necessary when the critical section data may be accessed by an interrupt handler

• int spin_trylock(spinlock_t *lock): 

Tries to acquire specified lock; returns nonzero if lock is currently held and zero otherwise

• int spin_is_locked(spinlock_t *lock): 

Returns nonzero if lock is currently held and zero otherwise

• void spin_unlock(spinlock_t *lock): 

Releases given lock

• void spin_unlock_irq(spinlock_t *lock): 

Releases given lock and enables local interrupts

More Related Content

What's hot

What's hot (20)

Waterfall model in SDLC
Waterfall model in SDLCWaterfall model in SDLC
Waterfall model in SDLC
 
Principles of Software testing
Principles of Software testingPrinciples of Software testing
Principles of Software testing
 
Server Side Technologies
Server Side TechnologiesServer Side Technologies
Server Side Technologies
 
Multimedia Database
Multimedia Database Multimedia Database
Multimedia Database
 
Spiral model presentation
Spiral model presentationSpiral model presentation
Spiral model presentation
 
Operating system 08 time sharing and multitasking operating system
Operating system 08 time sharing and multitasking operating systemOperating system 08 time sharing and multitasking operating system
Operating system 08 time sharing and multitasking operating system
 
Phases of Compiler
Phases of CompilerPhases of Compiler
Phases of Compiler
 
Important features of java
Important features of javaImportant features of java
Important features of java
 
Process of operating system
Process of operating systemProcess of operating system
Process of operating system
 
Multiprogramming&timesharing
Multiprogramming&timesharingMultiprogramming&timesharing
Multiprogramming&timesharing
 
Waterfall model
Waterfall modelWaterfall model
Waterfall model
 
2 phase locking protocol DBMS
2 phase locking protocol DBMS2 phase locking protocol DBMS
2 phase locking protocol DBMS
 
Transaction states and properties
Transaction states and propertiesTransaction states and properties
Transaction states and properties
 
Waterfall model
Waterfall modelWaterfall model
Waterfall model
 
Methods for handling deadlocks
Methods for handling deadlocksMethods for handling deadlocks
Methods for handling deadlocks
 
Transaction management DBMS
Transaction  management DBMSTransaction  management DBMS
Transaction management DBMS
 
Rad model
Rad modelRad model
Rad model
 
Acid properties
Acid propertiesAcid properties
Acid properties
 
10. XML in DBMS
10. XML in DBMS10. XML in DBMS
10. XML in DBMS
 
Segmentation in Operating Systems.
Segmentation in Operating Systems.Segmentation in Operating Systems.
Segmentation in Operating Systems.
 

Similar to Operating Systems 1 (8/12) - Concurrency

Synchronization problem with threads
Synchronization problem with threadsSynchronization problem with threads
Synchronization problem with threadsSyed Zaid Irshad
 
Non blocking programming and waiting
Non blocking programming and waitingNon blocking programming and waiting
Non blocking programming and waitingRoman Elizarov
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java ConcurrencyBen Evans
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating SystemsRitu Ranjan Shrivastwa
 
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...Gerke Max Preussner
 
West Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
West Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...West Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
West Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...Gerke Max Preussner
 
chapter4-processes nd processors in DS.ppt
chapter4-processes nd processors in DS.pptchapter4-processes nd processors in DS.ppt
chapter4-processes nd processors in DS.pptaakarshsiwani1
 
Operating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - SchedulingOperating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - SchedulingPeter Tröger
 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Sachintha Gunasena
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Multithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdfMultithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdfHarika Pudugosula
 
MODULE 3 process synchronizationnnn.pptx
MODULE 3 process synchronizationnnn.pptxMODULE 3 process synchronizationnnn.pptx
MODULE 3 process synchronizationnnn.pptxsenthilkumar969017
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaLuis Goldster
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaJames Wong
 

Similar to Operating Systems 1 (8/12) - Concurrency (20)

Synchronization problem with threads
Synchronization problem with threadsSynchronization problem with threads
Synchronization problem with threads
 
Non blocking programming and waiting
Non blocking programming and waitingNon blocking programming and waiting
Non blocking programming and waiting
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating Systems
 
Operating System lab
Operating System labOperating System lab
Operating System lab
 
Java threading
Java threadingJava threading
Java threading
 
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
 
West Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
West Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...West Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
West Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
 
ForkJoinPools and parallel streams
ForkJoinPools and parallel streamsForkJoinPools and parallel streams
ForkJoinPools and parallel streams
 
chapter4-processes nd processors in DS.ppt
chapter4-processes nd processors in DS.pptchapter4-processes nd processors in DS.ppt
chapter4-processes nd processors in DS.ppt
 
CHAP4.pptx
CHAP4.pptxCHAP4.pptx
CHAP4.pptx
 
Pthread
PthreadPthread
Pthread
 
Operating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - SchedulingOperating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - Scheduling
 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
 
Lecture 5 inter process communication
Lecture 5 inter process communicationLecture 5 inter process communication
Lecture 5 inter process communication
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Multithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdfMultithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdf
 
MODULE 3 process synchronizationnnn.pptx
MODULE 3 process synchronizationnnn.pptxMODULE 3 process synchronizationnnn.pptx
MODULE 3 process synchronizationnnn.pptx
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 

More from Peter Tröger

WannaCry - An OS course perspective
WannaCry - An OS course perspectiveWannaCry - An OS course perspective
WannaCry - An OS course perspectivePeter Tröger
 
Cloud Standards and Virtualization
Cloud Standards and VirtualizationCloud Standards and Virtualization
Cloud Standards and VirtualizationPeter Tröger
 
Distributed Resource Management Application API (DRMAA) Version 2
Distributed Resource Management Application API (DRMAA) Version 2Distributed Resource Management Application API (DRMAA) Version 2
Distributed Resource Management Application API (DRMAA) Version 2Peter Tröger
 
OpenSubmit - How to grade 1200 code submissions
OpenSubmit - How to grade 1200 code submissionsOpenSubmit - How to grade 1200 code submissions
OpenSubmit - How to grade 1200 code submissionsPeter Tröger
 
Design of Software for Embedded Systems
Design of Software for Embedded SystemsDesign of Software for Embedded Systems
Design of Software for Embedded SystemsPeter Tröger
 
Humans should not write XML.
Humans should not write XML.Humans should not write XML.
Humans should not write XML.Peter Tröger
 
What activates a bug? A refinement of the Laprie terminology model.
What activates a bug? A refinement of the Laprie terminology model.What activates a bug? A refinement of the Laprie terminology model.
What activates a bug? A refinement of the Laprie terminology model.Peter Tröger
 
Dependable Systems - Summary (16/16)
Dependable Systems - Summary (16/16)Dependable Systems - Summary (16/16)
Dependable Systems - Summary (16/16)Peter Tröger
 
Dependable Systems - Hardware Dependability with Redundancy (14/16)
Dependable Systems - Hardware Dependability with Redundancy (14/16)Dependable Systems - Hardware Dependability with Redundancy (14/16)
Dependable Systems - Hardware Dependability with Redundancy (14/16)Peter Tröger
 
Dependable Systems - System Dependability Evaluation (8/16)
Dependable Systems - System Dependability Evaluation (8/16)Dependable Systems - System Dependability Evaluation (8/16)
Dependable Systems - System Dependability Evaluation (8/16)Peter Tröger
 
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)Peter Tröger
 
Dependable Systems -Software Dependability (15/16)
Dependable Systems -Software Dependability (15/16)Dependable Systems -Software Dependability (15/16)
Dependable Systems -Software Dependability (15/16)Peter Tröger
 
Dependable Systems -Reliability Prediction (9/16)
Dependable Systems -Reliability Prediction (9/16)Dependable Systems -Reliability Prediction (9/16)
Dependable Systems -Reliability Prediction (9/16)Peter Tröger
 
Dependable Systems -Fault Tolerance Patterns (4/16)
Dependable Systems -Fault Tolerance Patterns (4/16)Dependable Systems -Fault Tolerance Patterns (4/16)
Dependable Systems -Fault Tolerance Patterns (4/16)Peter Tröger
 
Dependable Systems - Introduction (1/16)
Dependable Systems - Introduction (1/16)Dependable Systems - Introduction (1/16)
Dependable Systems - Introduction (1/16)Peter Tröger
 
Dependable Systems -Dependability Means (3/16)
Dependable Systems -Dependability Means (3/16)Dependable Systems -Dependability Means (3/16)
Dependable Systems -Dependability Means (3/16)Peter Tröger
 
Dependable Systems - Hardware Dependability with Diagnosis (13/16)
Dependable Systems - Hardware Dependability with Diagnosis (13/16)Dependable Systems - Hardware Dependability with Diagnosis (13/16)
Dependable Systems - Hardware Dependability with Diagnosis (13/16)Peter Tröger
 
Dependable Systems -Dependability Attributes (5/16)
Dependable Systems -Dependability Attributes (5/16)Dependable Systems -Dependability Attributes (5/16)
Dependable Systems -Dependability Attributes (5/16)Peter Tröger
 
Dependable Systems -Dependability Threats (2/16)
Dependable Systems -Dependability Threats (2/16)Dependable Systems -Dependability Threats (2/16)
Dependable Systems -Dependability Threats (2/16)Peter Tröger
 
Verteilte Software-Systeme im Kontext von Industrie 4.0
Verteilte Software-Systeme im Kontext von Industrie 4.0Verteilte Software-Systeme im Kontext von Industrie 4.0
Verteilte Software-Systeme im Kontext von Industrie 4.0Peter Tröger
 

More from Peter Tröger (20)

WannaCry - An OS course perspective
WannaCry - An OS course perspectiveWannaCry - An OS course perspective
WannaCry - An OS course perspective
 
Cloud Standards and Virtualization
Cloud Standards and VirtualizationCloud Standards and Virtualization
Cloud Standards and Virtualization
 
Distributed Resource Management Application API (DRMAA) Version 2
Distributed Resource Management Application API (DRMAA) Version 2Distributed Resource Management Application API (DRMAA) Version 2
Distributed Resource Management Application API (DRMAA) Version 2
 
OpenSubmit - How to grade 1200 code submissions
OpenSubmit - How to grade 1200 code submissionsOpenSubmit - How to grade 1200 code submissions
OpenSubmit - How to grade 1200 code submissions
 
Design of Software for Embedded Systems
Design of Software for Embedded SystemsDesign of Software for Embedded Systems
Design of Software for Embedded Systems
 
Humans should not write XML.
Humans should not write XML.Humans should not write XML.
Humans should not write XML.
 
What activates a bug? A refinement of the Laprie terminology model.
What activates a bug? A refinement of the Laprie terminology model.What activates a bug? A refinement of the Laprie terminology model.
What activates a bug? A refinement of the Laprie terminology model.
 
Dependable Systems - Summary (16/16)
Dependable Systems - Summary (16/16)Dependable Systems - Summary (16/16)
Dependable Systems - Summary (16/16)
 
Dependable Systems - Hardware Dependability with Redundancy (14/16)
Dependable Systems - Hardware Dependability with Redundancy (14/16)Dependable Systems - Hardware Dependability with Redundancy (14/16)
Dependable Systems - Hardware Dependability with Redundancy (14/16)
 
Dependable Systems - System Dependability Evaluation (8/16)
Dependable Systems - System Dependability Evaluation (8/16)Dependable Systems - System Dependability Evaluation (8/16)
Dependable Systems - System Dependability Evaluation (8/16)
 
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)
Dependable Systems - Structure-Based Dependabiilty Modeling (6/16)
 
Dependable Systems -Software Dependability (15/16)
Dependable Systems -Software Dependability (15/16)Dependable Systems -Software Dependability (15/16)
Dependable Systems -Software Dependability (15/16)
 
Dependable Systems -Reliability Prediction (9/16)
Dependable Systems -Reliability Prediction (9/16)Dependable Systems -Reliability Prediction (9/16)
Dependable Systems -Reliability Prediction (9/16)
 
Dependable Systems -Fault Tolerance Patterns (4/16)
Dependable Systems -Fault Tolerance Patterns (4/16)Dependable Systems -Fault Tolerance Patterns (4/16)
Dependable Systems -Fault Tolerance Patterns (4/16)
 
Dependable Systems - Introduction (1/16)
Dependable Systems - Introduction (1/16)Dependable Systems - Introduction (1/16)
Dependable Systems - Introduction (1/16)
 
Dependable Systems -Dependability Means (3/16)
Dependable Systems -Dependability Means (3/16)Dependable Systems -Dependability Means (3/16)
Dependable Systems -Dependability Means (3/16)
 
Dependable Systems - Hardware Dependability with Diagnosis (13/16)
Dependable Systems - Hardware Dependability with Diagnosis (13/16)Dependable Systems - Hardware Dependability with Diagnosis (13/16)
Dependable Systems - Hardware Dependability with Diagnosis (13/16)
 
Dependable Systems -Dependability Attributes (5/16)
Dependable Systems -Dependability Attributes (5/16)Dependable Systems -Dependability Attributes (5/16)
Dependable Systems -Dependability Attributes (5/16)
 
Dependable Systems -Dependability Threats (2/16)
Dependable Systems -Dependability Threats (2/16)Dependable Systems -Dependability Threats (2/16)
Dependable Systems -Dependability Threats (2/16)
 
Verteilte Software-Systeme im Kontext von Industrie 4.0
Verteilte Software-Systeme im Kontext von Industrie 4.0Verteilte Software-Systeme im Kontext von Industrie 4.0
Verteilte Software-Systeme im Kontext von Industrie 4.0
 

Recently uploaded

Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 

Recently uploaded (20)

Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 

Operating Systems 1 (8/12) - Concurrency

  • 1. Concurrency Beuth Hochschule Summer Term 2014 ! Pictures (C) W. Stallings, if not stated otherwise Pthread material from http://computing.llnl.gov/tutorials/pthreads ! ! „When two trains approach each other at a crossing, 
 both shall come to a full stop and neither shall start up again 
 until the other has gone.“
 [Kansas legislature, early 20th century]"
  • 3. ParProg | Introduction PT / FF 14 Abstraction of Concurrency [Breshears] • Processes / threads represent the execution of atomic statements • „Atomic“ can be defined on different granularity levels, e.g. source code line,
 so concurrency should be treated as abstract concept • Concurrent execution is the interleaving of atomic statements from multiple sequential processes • Unpredictable execution sequence of atomic instructions due to non-deterministic scheduling and dispatching, interrupts, and other activities • Concurrent algorithm should maintain properties for all possible inter-leavings • Example: All atomic statements are eventually included (fairness) • Some literature distinguishes between interleaving (uniprocessor) and 
 overlapping (multiprocessor) of statements - same problem 3
  • 4. ParProg | Introduction PT / FF 14 Concurrency • Management of concurrent activities in an operating system • Multiple applications in progress at the same time, non-sequential operating system activities • Time sharing for interleaved execution • Demands dispatching and synchronization • Parallelism: Actions are executed simultaneously • Demands parallel hardware • Relies on a concurrent application 4 Core Core time Thread1 Thread2 Thread1 Thread2 Memory Memory Core
  • 5. ParProg | Introduction PT / FF 14 Concurrency is Hard • Sharing of global resources • Concurrent reads and writes on the same variable makes order critical • Optimal management of resource allocation • Process gets control over a I/O channel and is then suspended before using it • Programming errors become non-deterministic • Order of interleaving may / may not activate the bug • Happens all with concurrent execution, which means even on uniprocessors • Race condition • The final result of an operation depends on the order of execution • Well-known issue since the 60‘s, identified by E. Dijkstra 5
  • 6. ParProg | Introduction PT / FF 14 Race Condition • Executed by two threads on uniprocessor • Executed by two threads on multiprocessor • What happens ? 6 void echo() { char_in = getchar(); char_out = char_in; putchar(char_out); } This is a „critical section“
  • 7. ParProg | Introduction PT / FF 14 Terminology • Deadlock („Verklemmung“) • Two or more processes / threads are unable to proceed • Each is waiting for one of the others to do something • Livelock • Two or more processes / threads continuously change their states in response to changes in the other processes / threads • No global progress for the application • Race condition • Two or more processes / threads are executed concurrently • Final result of the application depends on the relative timing of their execution 7
  • 8. ParProg | Introduction PT / FF 14 Potential Deadlock 8 I need quad A and B I need quad B and C I need quad C and B I need quad D and A
  • 9. ParProg | Introduction PT / FF 14 Actual Deadlock 9 HALT until B is free HALT until C is free HALT until D is free HALT until A is free
  • 10. ParProg | Introduction PT / FF 14 Terminology • Starvation („Verhungern“) • A runnable process / thread is overlooked indefinitely • Although it is able to proceed, it is never chosen to run (dispatching / scheduling) • Atomic Operation („Atomare Operation“) • Function or action implemented as a sequence of one or more instructions • Appears to be indivisible - no other process / thread can see an intermediate state or interrupt the operation • Executed as a group, or not executed at all • Mutual Exclusion („Gegenseitiger Ausschluss“) • The requirement that when one process / thread is using a resource, 
 no other shall be allowed to do that 10
  • 11. ParProg | Introduction PT / FF 1411 Example: The Dining Philosophers (E.W.Dijkstra) • Five philosophers work in a college, each philosopher has a room for thinking • Common dining room, furnished with a circular table, 
 surrounded by five labeled chairs • In the center stood a large bowl of spaghetti, which was constantly replenished • When a philosopher gets hungry: • Sits on his chair • Picks up his own fork on the left and plunges
 it in the spaghetti, then picks up the right fork • When finished he put down both forks 
 and gets up • May wait for the availability of the second fork
  • 12. ParProg | Introduction PT / FF 14 Example: The Dining Philosophers (E.W.Dijkstra) • Idea: Shared memory synchronization has different standard issues • Explanation of deadly embrace (deadlock) and starvation (livelock) • Forks taken one after the other, released together • No two neighbors may eat at the same time • Philosophers as tasks, forks as shared resource • How can a deadlock happen ? • All pick the left fork first and wait for the right • How can a live-lock (starvation) happen ? • Two fast eaters, sitting in front of each other • One possibility: Waiter solution (central arbitration) 12 (C)Wikipedia
  • 13. ParProg | Introduction PT / FF 14 Critical Section • n threads all competing to use a shared resource (i.e.; shared data, spaghetti forks) • Each thread has some code - critical section - in which the shared data is accessed • Mutual Exclusion demand • Only one thread at a time is allowed into its critical section, among all threads that have critical sections for the same resource. • Progress demand • If no other thread is in the critical section, the decision for entering should not be postponed indefinitely. Only threads that wait for entering the critical section are allowed to participate in decisions. (deadlock problem) • Bounded Waiting demand • It must not be possible for a thread requiring access to a critical section to be delayed indefinitely by other threads entering the section. (starvation problem) 13
  • 14. ParProg | Introduction PT / FF 14 Critical Section • Only 2 threads, T0 and T1 • General structure of thread Ti (other thread Tj) • Threads may share some common variables to synchronize their actions 14 do { enter section critical section exit section reminder section } while (1);
  • 15. ParProg | Introduction PT / FF 14 Critical Section Protection with Hardware • Traditional solution was interrupt disabling, but works only on multiprocessor • Concurrent threads cannot overlap on one CPU • Thread will run until performing a system call or interrupt happens • Software-based algorithms also do not work, due to missing atomic statements • Modern architectures need hardware support with atomic machine instructions • Test and Set instruction - 
 read & write memory at once • If not available, atomic swap 
 instruction is enough • Busy waiting, starvation or 
 deadlock are still possible 15 #define LOCKED 1! int TestAndSet(int* lockPtr) {! int oldValue;! oldValue = SwapAtomic(lockPtr, LOCKED);! return oldValue;! } function Lock(int *lock) {! while (TestAndSet (lock) == LOCKED);! }
  • 16. 16 „Manual“ implementation! of a critical section for ! interleaved output
  • 17. ParProg | Introduction PT / FF 14 Binary and General Semaphores [Dijkstra] • Find a solution to allow waiting processes 
 to ,sleep‘ • Special purpose integer called semaphore • P-operation: Decrease value of its argument 
 semaphore by 1 as atomic step • Blocks if the semaphore is already zero -
 wait operation • V-operation: Increase value of its argument 
 semaphore by 1 as atomic step • Releases one instance of the resource 
 for other processes - signal operation • Solution for critical section shared between N processes • Binary semaphore has initial value of 1, counting semaphore of N 17 wait (S): while (S <= 0); S--; // atomic signal (S): S++; // atomic do { wait(mutex); critical section signal(mutex);
 remainder section } while (1);
  • 18. ParProg | Introduction PT / FF 14 Semaphores and Busy Wait • Semaphores may suspend/resume threads to avoid busy waiting • On wait operation • Decrease value • When value <= 0, calling thread is suspended and added to waiting list • Value may become negative with multiple waiters • On signal operation • Increase value • When value <= 0, one waiting thread is
 woken up and remove from the waiting list 18 typedef struct { int value; struct thread *L; } semaphore;
  • 19. ParProg | Introduction PT / FF 14 Shared Data Protection by Semaphores 19
  • 20. ParProg | Introduction PT / FF 14 POSIX Pthreads • Part of the POSIX specification collection, defining an API for thread creation and management (pthread.h) • Implemented by all (!) Unix-alike operating systems available • Utilization of kernel- or user-mode threads depends on implementation • Groups of functionality (pthread_ function prefix) • Thread management - Start, wait for termination, ... • Mutex-based synchronization • Synchronization based on condition variables • Synchronization based on read/write locks and barriers • Semaphore API is a separate POSIX specification (sem_ prefix) 20
  • 21. ParProg | Introduction PT / FF 14 POSIX Pthreads 21
  • 22. ParProg | Introduction PT / FF 14 POSIX Pthreads 22 • pthread_create() • Create new thread in the process, with given routine and argument • pthread_exit(), pthread_cancel() • Terminate thread from inside our outside of the thread • pthread_attr_init() , pthread_attr_destroy() • Abstract functions to deal with implementation-specific attributes
 (f.e. stack size limit) • See discussion in man page about how this improves portability int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg);
  • 23. 23 /******************************************************************************! * FILE: hello.c! * DESCRIPTION:! * A "hello world" Pthreads program. Demonstrates thread creation and! * termination.! * AUTHOR: Blaise Barney! * LAST REVISED: 08/09/11! ******************************************************************************/! #include <pthread.h>! #include <stdio.h>! #include <stdlib.h>! #define NUM_THREADS! 5! ! void *PrintHello(void *threadid)! {! long tid;! tid = (long)threadid;! printf("Hello World! It's me, thread #%ld!n", tid);! pthread_exit(NULL);! }! ! int main(int argc, char *argv[])! {! pthread_t threads[NUM_THREADS];! int rc;! long t;! for(t=0;t<NUM_THREADS;t++){! printf("In main: creating thread %ldn", t);! rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);! if (rc){! printf("ERROR; return code from pthread_create() is %dn", rc);! exit(-1);! }! }! ! /* Last thing that main() should do */! pthread_exit(NULL);! }
  • 24. ParProg | Introduction PT / FF 14 POSIX Pthreads 24 • pthread_join() • Blocks the caller until the specific thread terminates • If thread gave exit code to pthread_exit(), it can be determined here • Only one joining thread per target is thread is allowed • By the book, threads should be joinable (old implementations problem) • pthread_detach() • Mark thread as not-joinable (detached) - may free some system resources • pthread_attr_setdetachstate() • Prepare attr block so that a thread can be created in some detach state int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
  • 25. ParProg | Introduction PT / FF 14 POSIX Pthreads 25
  • 26. 26 /*****************************************************************************! * FILE: join.c! * AUTHOR: 8/98 Blaise Barney! * LAST REVISED: 01/30/09! ******************************************************************************/! #include <pthread.h>! #include <stdio.h>! #include <stdlib.h>! #define NUM_THREADS! 4! ! void *BusyWork(void *t) {! int i;! long tid;! double result=0.0;! tid = (long)t;! printf("Thread %ld starting...n",tid);! for (i=0; i<1000000; i++) {! result = result + sin(i) * tan(i); }! printf("Thread %ld done. Result = %en",tid, result);! pthread_exit((void*) t); }! ! int main (int argc, char *argv[]) {! pthread_t thread[NUM_THREADS];! pthread_attr_t attr;! int rc; long t; void *status;! ! pthread_attr_init(&attr);! pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);! ! for(t=0; t<NUM_THREADS; t++) {! printf("Main: creating thread %ldn", t);! rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t); ! if (rc) {! printf("ERROR; return code from pthread_create() is %dn", rc);! exit(-1);}}! ! pthread_attr_destroy(&attr);! for(t=0; t<NUM_THREADS; t++) {! rc = pthread_join(thread[t], &status);! if (rc) {! printf("ERROR; return code from pthread_join() is %dn", rc);! exit(-1); }! printf("Main: completed join with thread %ld having a status of %ldn",t,(long)status);}! ! printf("Main: program completed. Exiting.n");! pthread_exit(NULL); }
  • 27. ParProg | Introduction PT / FF 14 POSIX Pthreads 27 • pthread_mutex_init() • Initialize new mutex, which is unlocked by default • pthread_mutex_lock(), pthread_mutex_trylock() • Blocking / non-blocking wait for a mutex lock • pthread_mutex_unlock() • Operating system scheduling decides about wake-up preference • Focus on speed of operation, no deadlock or starvation protection mechanism int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_trylock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex);
  • 28. ParProg | Introduction PT / FF 14 Windows vs. POSIX Synchronization 28 Windows POSIX WaitForSingleObject pthread_mutex_lock() WaitForSingleObject(timeout==0) pthread_mutex_trylock() Auto-reset events Condition variables
  • 29. ParProg | Introduction PT / FF 14 Spinlocks 29 Processor'B'Processor'A' do# ####acquire_spinlock(DPC)# un6l#(SUCCESS)# # begin# ####remove#DPC#from#queue# end# # release_spinlock(DPC)# do# ####acquire_spinlock(DPC)# un6l#(SUCCESS)# # begin# ####remove#DPC#from#queue# end# # release_spinlock(DPC)# .# .# .# .# .# .# Cri6cal#sec6on# spinlock# DPC# DPC#
  • 30. ParProg | Introduction PT / FF 14 Spinlocks 30 Try$to$acquire$spinlock:$ Test,$set,$was$set,$loop$ Test,$set,$was$set,$loop$ Test,$set,$was$set,$loop$ Test,$set,$was$set,$loop$ Test,$set,$WAS$CLEAR$ (got$the$spinlock!)$ Begin$updaCng$data$ Try$to$acquire$spinlock:$ Test,$set,$WAS$CLEAR$ (got$the$spinlock!)$ Begin$updaCng$data$ $that’s$protected$by$the$ $spinlock$ $ $ (done$with$update)$ Release$the$spinlock:$ Clear$the$spinlock$bit$ $ CPU$1$ CPU$2$
  • 31. ParProg | Introduction PT / FF 14 Windows: Queued Spinlocks • Problem: Checking status of spinlock via test-and-set creates bus contention • Idea of queued spinlocks: • Each spinlock maintain a queue of waiting processors • First processor acquires the lock directly • Other processors are added to the queue and spin on a local wait bit • On release, the according processor resets the wait bit of the next CPU in queue • Exactly one processor is being signaled • Pre-determined wait order • Result: Busy-wait loops of all CPUs require 
 no access to main memory • (Check reading list for details) 31
  • 32. ParProg | Introduction PT / FF 14 Linux: Spinlocks • Common critical section strategy in the Linux kernel • Uniprocessor system with disabled kernel preemption: • Kernel threads are never interrupted, so locks are deleted at compile time • Uniprocessor system with enabled kernel preemption: • Spinlock code is replaced with disabling / enabling of interrupts • Multiprocessor system • Spinlock code compiled into monolithic kernel • Additional support for reader-writer spinlocks, which favor the reader • Similar API for portability 32
  • 33. ParProg | Introduction PT / FF 14 Linux: Spinlocks 33 • void spin_lock_init(spinlock_t *lock): 
 Initializes given spinlock • void spin_lock(spinlock_t *lock): 
 Acquires the specified lock, spinning if needed until it is available • void spin_lock_irq(spinlock_t *lock): 
 Like spin_lock(), but also disables interrupts on the local processor • Necessary when the critical section data may be accessed by an interrupt handler • int spin_trylock(spinlock_t *lock): 
 Tries to acquire specified lock; returns nonzero if lock is currently held and zero otherwise • int spin_is_locked(spinlock_t *lock): 
 Returns nonzero if lock is currently held and zero otherwise • void spin_unlock(spinlock_t *lock): 
 Releases given lock • void spin_unlock_irq(spinlock_t *lock): 
 Releases given lock and enables local interrupts