Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Tasks and Threads

Download as pdf or txt
Download as pdf or txt
You are on page 1of 104

OS : Tasks And Threads

Ludovic Saint-Bauzel
Polytech'Pqris UPMC

2011-2012
Scheduling Model

Layout

Scheduling
Model
Algorithms
Thread Scheduling

Management

Time Services

Synchronization

Messages and Communication

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 2 / 104


Scheduling Model

Scheduler

Aim : address any needs of a real-time software like emergency stop, high

level action or reactivity need


Taxonomy :
I O-line/On-line algorithm : static/dynamic algorithm
I Static/Dynamic priorities
I pre-emptive/non pre-emptive algorithms :
I Ability to have mutual exclusion of a device
I Scheduler cost low
I Small ecient

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 3 / 104


Scheduling Model

Scheduler

Properties that we look for :


I Feasibility : ability to decide "a priori" that all the constraints will be
fullled
I Predictability : response time of tasks is predictable.
I Optimality : Optimal if able to nd a schedule of every set of
feasibility tasks
I Complexity : feasibility test is long and dicult?
I Easiness to implement

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 4 / 104


Scheduling Model

Scheduler

Scheduler works only on active tasks :


I Schedule Table : o-line scheduling
I O-line priorities denition, root of the scheduling
I On-line analysis and scheduling

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 5 / 104


Scheduling Model

Analysis recipe

Scheduling problem :
I To Model tasks of the system and their constraints
I To Choose a scheduling algorithm
I To Validate feasibility on a set of tasks
I Theoretical feasibility : scheduling ability and complexity
I Empirical feasibility : implement scheduler

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 6 / 104


Scheduling Model

Task model

Task families :
I Linked task or not (Precedence constraint).
I Important task or not
I Repetitive or periodic task : activated regularly
I Non periodic task
I Sporadic : irregular activation but a minimum time between each
activation
I Aperiodic : deadline is less strict and no minimum time between each
activation

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 7 / 104


Scheduling Model

Task model

Parameters for task i


I Si : start time when task arrives in the scheduler
I Ci : Computation time needed by the task (Capacity).
I Pi : Period
I Di : Deadline of the task
I Ri : Earliest activation time
I Aperiodic task is dened by :

(Si , Ci , Di , Ri )
I Periodic task is dened by :
(Si , Ci , Di , Pi )

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 8 / 104


Scheduling Model

Task model

Let's consider a simplied model :


I Periodic task
I Independent (No precedence constraint)
I Starting time (worst case) : Si = 0
I Deadline equal to Period : Pi = Di

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 9 / 104


Scheduling Model

Scheduler Structure

Computation of scheduling information


I On-line or O-line
I Period, Deadline...

Waiting queue management


I One queue for each priority
I FIFO policy
I Round Robin policy

Election phase
I Priority, deadline, ...

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 10 / 104


Scheduling Algorithms

Layout

Scheduling
Model
Algorithms
Thread Scheduling

Management

Time Services

Synchronization

Messages and Communication

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 11 / 104


Scheduling Algorithms

Rate Monotonic Algorithm

O-line analysis, xed priority, periodic tasks : Static software


Rationale

I Computation phase : priority = period 1

I Election phase : highest priority is chosen


Properties

I Low Complexity
I Optimal Algorithm in xed priority algorithm set

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 12 / 104


Scheduling Algorithms

Rate Monotonic Algorithm

Example

I Task 1 : C = 6, P = 10
1 1

I Task 2 : C = 9, P = 30
2 1

I Pre-emptive case
I Non pre-emptive case
Can be scheduled if load rate of the CPU U agrees with the following
sucient condition :
n i ≤ n × (2 − 1)
C
=∑
1
U n

i Ti

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 13 / 104


Scheduling Algorithms

Critical time theorem

If every tasks both arrive at the same time in a system if they respect their
rst deadline,
then
every other following deadlines will be respected whatever time they arrive
in the system
I it's a necessary and sucient condition if every tasks arrive at the
same time
I else, it is a sucient condition
If Di = Ti , nishing test is :
i C j

t

∀i , 1 ≤ i ≤ n min ≤t ≤D
0 ∑ j
≤1
j=
i
t T
1

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 14 / 104


Scheduling Algorithms

Response time computation

Response time TR: Duration between time when a task begin and time
when it is nished. Result can be exact relying on task model.

TR i = Ci + ∑ j I

j ∈hp (i )
i
 
TR
TR i = Ci + ∑ j
j
C

j ∈hp (i ) P

Where hp (i ) represents a set of tasks with a higher priority than i .

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 15 / 104


Scheduling Algorithms

Response time computation

Computation method : iterative way of evaluation


 n
n+ = C +
∑ Pij Cj
w
i
1
w
i
j ∈hp (i )

I Let start with wi = Ci 0

I Fail if win > Pi


I Achieved if win+ = win 1

Example : with P = 7, C = 3, P = 12, C = 2, P = 20, C = 5. We


1 1 2 2 3 3

assume that every task have the same priority and are ran in this order
TR1 =3 TR2 =5 TR3 = 18

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 16 / 104


Scheduling Algorithms

Aperiodic tasks with high priorities

Periodic task dedicated to these tasks.


I bring feasibility in the worst case
I dedicated task is not activated if there is no aperiodic task to compute
I easy solution, but sometime we loose some CPU load

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 17 / 104


Scheduling Algorithms

Earliest Deadline First EDF algorithm

I Periodic task and aperiodic


I On-line Algorithm, more useful than Rate Monotonic
Rationale :

I Computation phase : Deadline computation

With priorityi (t ) current priority at t and i the task :


I Aperiodic task : priority (t ) = S + D − t
i i i
I Periodic task : priority (t ) = S (t ) [last start activation time when
i i
time is t] +Pi − t
I Election phase : Earliest deadline is chosen.(Min)

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 18 / 104


Scheduling Algorithms

EDF Example

Let consider 2 tasks :


T1 : C1 = 6, P1 = 10
T2 : C2 = 9, P2 = 30
I Pre-emptive case
I Non pre-emptive case

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 19 / 104


Scheduling Algorithms

EDF Properties

Ability to schedule : Pre-emptive case, periodic and independent tasks


I Necessary and sucient condition if ∀i , Di = Pi ; Only necessary if
∃i , Di ≤ Pi :
n Cj
U = ∑ ≤1
j = Pj 1

I Sucient condition if ∃i , Di ≤ Pi :
n Cj
U = ∑ ≤1
j = Dj 1

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 20 / 104


Scheduling Algorithms

Server for aperiodic and sporadic jobs

I Periodic server :
I Idle if waiting queue is empty
I Running in its time

PS

e1

e2

0 5 10 15 20

e1 e2

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 21 / 104


Scheduling Algorithms

Server for aperiodic and sporadic jobs


I Deferred server :
I Time Budget
I Waiting for task
I Used to be in highest priority

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 22 / 104


Scheduling Algorithms

Server for aperiodic and sporadic jobs


I Sporadic server :
I Like Deferred server
I But extra computation is done in background (lowest priority)

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 23 / 104


Scheduling Thread Scheduling

Layout

Scheduling
Model
Algorithms
Thread Scheduling

Management

Time Services

Synchronization

Messages and Communication

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 24 / 104


Scheduling Thread Scheduling

Services

Properties :
I Threads and process capability
I Fixed priorities, pre-emptive ⇒ RM easy. A minimum of 32 levels is a
mandatory
I One waiting queue for each priority and scheduling policy (SCHED_F
IFO, SCHED_RR, SCHED_OTHERS).
I Available Services to specic users (like root)

Standard say that scheduling policies must be able to be applied each time
the choice threadprocess exists (ex. : choice of a threadprocess to release a
semaphore).

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 25 / 104


Scheduling Thread Scheduling

Policies

POSIX.4 policies :
# define SCHED_OTHER 0
# define SCHED_FIFO 1
# define SCHED_RR 2

I Parameter(s) : extensible to future policies


struct sched_param {
int sched_priority ;
...
};

I Parameters modication:
I Thread : creation of a thread from an attribute or modication of a
running thread.
I Inherit from a fork() or modify of a running process.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 26 / 104


Scheduling Thread Scheduling

API

sched_get_priority_max Get max priority value.


sched_get_priority_min Get min priority value.
sched_rr_get_interval Get duration of one time unit.
sched_yield Free the CPU of this thread.
sched_setscheduler Choose the scheduler policy.
sched_getscheduler Get the scheduler policy value.
sched_setparam Set parameters of the scheduler.
sched_getparam Get parameters of the scheduler.
pthread_setschedparam Set parameters of the scheduler for thread.
pthread_getschedparam Get parameters of the scheduler for thread.
The last 2 function are working only on threads, other functions can be
applied on process/thread.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 27 / 104


Scheduling Thread Scheduling

Example

struct sched_param parm ;


int res = -1;
...
/* Task T1 ; P1 =10 */
parm . sched_priority =15;
res = sched_setscheduler ( pid_T1 , SCHED_FIFO ,& parm )
if ( res <0)
perror (" sched_setscheduler task T1 ");
/* Task T2 ; P2 =30 */
parm . sched_priority =10;
res = sched_setscheduler ( pid_T2 , SCHED_FIFO ,& parm )
if ( res <0)
perror (" sched_setscheduler task T2 ");

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 28 / 104


Management Process

Layout

Scheduling

Management
Process
Posix Thread

Time Services

Synchronization

Messages and Communication

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 29 / 104


Management Process

Fork

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 30 / 104


Management Process

Kill - Signal

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 31 / 104


Management Posix Thread

Layout

Scheduling

Management
Process
Posix Thread

Time Services

Synchronization

Messages and Communication

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 32 / 104


Management

POSIX Threads

Dened in chapter POSIX.4a. This chapter describe both threads and


synchronization tools that are close to threads (ex : mutex).
Properties :
I A POSIX Thread is dened with a identier that is local to the
process.It owns its stack, its context and a set of attributes that
describe its behaviour.
I A POSIX Thread can be implemented in user space or in kernel space
⇒ Standard describe only the interface not the way it is coded.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 33 / 104


Management

POSIX Threads

I Code must be re-entrant (or "thread safe") ⇒ code is able to be


computed in multiple instances in a safe way
I re-entrant code means :
I don't manipulate shared variables.
I or it manipulate shared variables in a critical section (that mean no
other is able to access this variable when one is manipulating it) .
I Everything must be re-entrant user code but also system libraries (ex.
libc.so)

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 34 / 104


Management

POSIX threads

pthread_create Creation of a thread.


Paramters : code, attributes, arg.
pthread_exit End of a thread.
Parameter : return error value.
pthread_self returns id of the running thread
pthread_cancel Destroy a thread.
Parameter : id of the thread.
pthread_join Suspend a thread until
another is not nished.
pthread_detach Suppress parent link
between threads.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 35 / 104


Management

POSIX Threads

pthread_kill Emit a signal to a thread.


pthread_sigmask Modify signal mask of a thread.
In a POSIX.4a system, some services have a dierent semantic.
I fork() : create a new process containing a thread where the main()
function is computed
I exit() : nish a process and all threads it contains.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 36 / 104


Management

POSIX Threads

Creation and join example of a thread


# include < pthread .h >
void * th ( void * arg )
{
printf (" I am thread % d ;
process % d \ n " ,
pthread_self () , getpid ());
pthread_exit ( NULL );
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 37 / 104


Management

POSIX Threads

Creation and join example of a thread


# include < pthread .h >
void * th ( void * arg )
{
printf (" I am thread % d ;
process % d \ n " ,
pthread_self () , getpid ());
pthread_exit ( NULL );
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 38 / 104


Management

POSIX Threads

int main ( int argc , char * argv [])


{
pthread_t id1 , id2 ;
pthread_create (& id1 , NULL , th , NULL );
pthread_create (& id2 , NULL , th , NULL );
pthread_join ( id1 , NULL );
pthread_join ( id2 , NULL );
printf (" End of main thread % d ;
process % d \ n " ,
pthread_self () , getpid ());
pthread_exit ( NULL );
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 39 / 104


Management

POSIX Threads

I With Solaris :
gcc - D_REENTRANT create . c - lpthread - lrt
>a . out
I am thread 4 ; process 5539
I am thread 5 ; process 5539
End of main thread 1 ; process 5539

I With Linux :
gcc - D_REENTRANT create . c - lpthread
>a . out
I am thread 1026 ; process 1253
I am thread 2051 ; process 1254
End of main thread 1024 ; process 1251

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 40 / 104


Management

Thread Attributes

Thread Attributes : properties of a thread that are dened during its


creation. No heritage between father and son threads.
Example of attributes :
Attribute Name Meaning
detachstate pthread_join possible or not
policy scheduler policy
priority level of priority of the thread (≥ 0)
stacksize Size of the allocated stack

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 41 / 104


Management

Thread Attributes

During creation of a thread, an structure of type pthread_attr_t can be


lled and given if we want to specify none default attributes to the new
thread :
pthread_attr_init Creation of a default attribute structure.
pthread_attr_delete Destruction of attribute structure.
pthread_attr_setATT set the value of "ATT" attribute.
pthread_attr_getATT set the value of "ATT" attribute.
where ATT is replace by the name of the attribute.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 42 / 104


Management

Thread Attributes

# include < pthread .h >


void * th ( void * arg )
{
printf (" I am thread % d \ n " ,
pthread_self ());
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 43 / 104


Management

Thread Attributes

int main ( int argc , char * argv [])


{
int i;
pthread_t id ;
pthread_attr_t attr ;
struct sched_param param ;
pthread_attr_init (& attr );
pthread_attr_setdetachstate (& attr ,
PTHREAD_CREATE_DETACHED );
pthread_attr_setschedpolicy (& attr ,
SCHED_FIFO );
param . sched_priority =1;
pthread_attr_setschedparam (& attr ,& param );
for ( i =1; i <10; i ++)
pthread_create (& id ,& attr , th , NULL );
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 44 / 104


Management

Thread Attributes

The TSD (Thread Specic Data area) : is an area of memory where are
stored specic information of each thread.
Allow extension of regular attributes.
pthread_key_create Creation of a key.
pthread_key_delete Destruction of the key.
pthread_getspecic get pointer value linked
to the key of the running thread.
pthread_setspecic set pointer value linked
to the key of the running thread.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 45 / 104


Management

Thread Attributes

Creation of a new attribute :


pthread_key_t cd_key ;

int pthread_cd_init ( void )


{
return pthread_key_create (& cd_key , NULL );
}

char * pthread_get_cd ( void )


{
return ( char *) pthread_getspecific ( cd_key );
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 46 / 104


Management

Thread Attributes

int pthread_set_cd ( char * cd )


{
char * mycd = ( char *) malloc ( sizeof ( char )*100);
strcpy ( mycd , cd );
return pthread_setspecific ( cd_key , mycd );
}
int main ( int argc , char * argv [])
{
pthread_cd_init ();
pthread_set_cd ("/ here / dir ");
printf (" My local directory is % s \ n " ,
pthread_get_cd ());
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 47 / 104


Time Services Posix Time

Layout

Scheduling

Management

Time Services
Posix Time
Xenomai Time services

Synchronization

Messages and Communication

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 48 / 104


Time Services Posix Time

Time manipulation

Time linked services :


I What time is it ?
I Block a thread/process during a dened time.
I Wake up a thread/process regularly (timer) ⇒ periodic tasks.

Precision of these services :


I Linked to what hardware we have (clock circuit), its features
(interruption period) and also to the software that use it (interruption
handler).
I Ex : Linux Intel : circuit activated periodically (10 ms) ⇒ waking
between 10 to 12 ms.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 49 / 104


Time Services Posix Time

Time Manipulation : POSIX Extensions

I Many timers are available ⇒ many physical clocks, proling.


I Need at least one real-time clock : CLOCK_REALTIME (less than 20
ms precise).
I timespec structure ⇒ "theoretical" precision close to micro-seconds
....
I Available services :
I Get and set clocks.
I Put a task in sleep mode.
I Link periodic timer to UNIX signals ; and maybe with real-time
signals. With or without automatic restart.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 50 / 104


Time Services Posix Time

Time Manipulation

clock_gettime Get clock value.


clock_settime Set clock value.
clock_getres Get clock resolution.
timer_create Create a timer.
timer_delete Remove a timer.
timer_getoverrrun Give the number of unprocessed signals
timer_settime Activate a timer.
timer_gettime Get time to the end of the timer
nanosleep Block a process/thread during a
dened duration.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 51 / 104


Time Services Posix Time

make

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 52 / 104


Time Services Posix Time

Time Manipulation : Example

int main ( int argc , char * argv []){


timer_t monTimer ; struct sigaction sig ;
struct itimerspec ti ;
timer_create ( CLOCK_REALTIME , NULL ,& monTimer );
sig . sa_flags = SA_RESTART ;
sig . sa_handler = trop_tard ;
sigemptyset (& sig . sa_mask );
sigaction ( SIGALRM ,& sig , NULL );
ti . it_value . tv_sec = capacite ;
ti . it_value . tv_nsec =0;
ti . it_interval . tv_sec =0; // here timer is not
ti . it_interval . tv_nsec =0; // automatically restarted
timer_settime ( monTimer ,0 ,& ti , NULL );

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 53 / 104


Time Services Posix Time

Time Manipulation : Example


printf (" Begin \ n ");
while ( go >0)
printf (" I am working .....\ n ");
printf (" Unblocked by timer : deadline missed ..\ n ");
}

int go =1;
void too_late ( int sig ){
printf (" Signal % d received \ n " , sig );
go =0;
}

Execution :

Begin I am working .....


I am working ..... I am working .....
I am working ..... Signal 14 received
I am working ..... Unblocked by timer : deadline missed

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 54 / 104


Time Services Xenomai Time services

Layout

Scheduling

Management

Time Services
Posix Time
Xenomai Time services

Synchronization

Messages and Communication

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 55 / 104


Time Services Xenomai Time services

API Timer Management System

API :
I void rt_timer_spin (RTIME ns) : busy clock
I int rt_timer_set_mode (RTIME nstick) : TM_ONESHOT or
period time
Hardware level :
I oneshot
I periodic

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 56 / 104


Synchronization Mutex

Layout

Scheduling

Management

Time Services

Synchronization
Mutex
Cond Var
Counting Semaphore
Xenomai Native API Synchronisation tools

Messages and Communication

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 57 / 104


Synchronization Mutex

Mutex

I Optimized Semaphores to implement critical section.


I Waiting queue manager : depends of scheduling policy
(SCHED_FIFO, SCHED_OTHER, ...). Default behaviour : threads
are waked in decreasing order of priority
I Behaviour is dened by a set of attributes, main parameters are :
Attribute name Meaning
protocol Inheriting Protocol used
pshared Inter-process or inter-thread mutex
ceiling Priority ceiling

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 58 / 104


Synchronization Mutex

Mutex

pthread_mutex_init Initialize a mutex.


pthread_mutex_lock Lock the mutex in blocking manner eventuall
pthread_mutex_trylock Non blocking try to lock the mutex
pthread_mutex_unlock Release the mutex lock.
pthread_mutex_destroy Destruct the mutex.
pthread_mutexattr_init Initialize an attribute structure
pthread_mutexattr_setATT Set attribute ATT.
pthread_mutexattr_getATT Get attribute ATT value.
o ATT is one of the attributes of the mutex.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 59 / 104


Synchronization Cond Var

Layout

Scheduling

Management

Time Services

Synchronization
Mutex
Cond Var
Counting Semaphore
Xenomai Native API Synchronisation tools

Messages and Communication

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 60 / 104


Synchronization Cond Var

Rationale

Programming mechanism that can block a thread while a condition is not


true.

I Solution is based on a mutex and a Var Cond


I Waking signal has no memory : if nothing is waiting for the condition,
waking signal is lost (6= counting semaphores).
I Waiting queue management : depend on scheduling policy
(SCHED_FIFO, SCHED_OTHER, etc ...). Default behaviour :
threads are waked in decreasing order of priority.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 61 / 104


Synchronization Cond Var

API

pthread_cond_init Initialize a variable.


pthread_cond_destroy Destruct a variable.
pthread_cond_wait Wait a waking signal coming from a condition.
pthread_cond_signal Signal that a condition is true to one thread
pthread_cond_broadcast Signal that a condition is true to all threads

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 62 / 104


Synchronization Cond Var

Mechanism

A classical program where a thread modify a variable : a mutex is used


(var_mutex) and a condition is used (var_cond).
pthread_mutex_lock (& var_mutex );
/* Modify the variable in critical
section */
var = .... ;

/* If the condition is fulfilled , we


alert the blocked thread */
if ( condition ( var ))
pthread_cond_signal (& var_cond );

pthread_mutex_unlock (& var_mutex );

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 63 / 104


Synchronization Cond Var

Mechanism

Classical program that wait for a variable to be modied :


pthread_mutex_lock (& var_mutex );
while (! condition ( var ))
{
/* If the condition is not true ,
wait */
pthread_cond_wait (& var_cond , & var_mutex );
}
/* use the variable in critical section */
.....

pthread_mutex_unlock (& var_mutex );

Attention pthread_cond_wait is making some implicit lock and unlock of


the mutex.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 64 / 104


Synchronization Cond Var

Example

int y =2 , x =0;
pthread_mutex_t mut ;
pthread_cond_t cond ;
void * th ( void * arg )
{
int cont =1;
while ( cont ){
pthread_mutex_lock (& mut );
x ++;
printf (" x ++\ n ");
if ( x > y ){
pthread_cond_signal (& cond );
cont =0; }
pthread_mutex_unlock (& mut );}
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 65 / 104


Synchronization Cond Var

Example

int main ( int argc , char * argv ){


pthread_t id ;
pthread_mutex_init (& mut , NULL );
pthread_cond_init (& cond , NULL );
pthread_mutex_lock (& mut );
pthread_create (& id , NULL , th , NULL );
while ( x <= y )
pthread_cond_wait (& cond , & mut );
printf (" x > y is true \ n ");
pthread_mutex_unlock (& mut );}

Execution :
x ++ x ++
x ++ x > y is true

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 66 / 104


Synchronization Counting Semaphore

Layout

Scheduling

Management

Time Services

Synchronization
Mutex
Cond Var
Counting Semaphore
Xenomai Native API Synchronisation tools

Messages and Communication

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 67 / 104


Synchronization Counting Semaphore

Counting semaphore

I Semaphore: waiting queue + counter.


I No management of priority inversion : case must be treated in
developer level.
I Used for synchronization and inter-process or inter-thread mutual
exclusion.
I Waiting queue management : depend on scheduling policy
(SCHED_FIFO, SCHED_OTHER, etc ...). Default behaviour :
threads are waked in decreasing order of priority.
I Two kind of semaphore : named and unnamed semaphore.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 68 / 104


Synchronization Counting Semaphore

Counting Semaphore

sem_open Connection to a named semaphore.


sem_close Disconnection to a named semaphore.
sem_unlink Destruction of a named semaphore.
sem_init Initialisation of a unnamed semaphore..
sem_destroy Destruction of a unnamed semaphore.
sem_post Freeing a semaphore.
sem_wait Acquiring a semaphore.
sem_trywait Non blocking acquiring of a semaphore.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 69 / 104


Synchronization Counting Semaphore

Counting Semaphore Example

# include < pthread .h >


# include < semaphore .h >
sem_t sem ;
int main ( int argc , char * argv []){
pthread_t id ;
struct timespec delay ;
sem_init (& sem ,0 ,0);
pthread_create (& id , NULL , th , NULL );
deli . tv_sec =4; deli . tv_nsec =0;
nanosleep (& delay , NULL );
printf (" main thread % d : free from
the other thread \ n " , pthread_self ());
sem_post (& sem );
pthread_exit ( NULL );
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 70 / 104


Synchronization Counting Semaphore

Counting Semaphore Example

void * th ( void * arg )


{
printf (" thread % d waiting \ n " ,
pthread_self ());
sem_wait (& sem );
printf (" thread % d unblocked \ n " ,
pthread_self ());
}

Execution

thread 4 waiting
main thread 1 : free from
the other thread
thread 4 unblocked

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 71 / 104


Synchronization Xenomai Native API Synchronisation tools

Layout

Scheduling

Management

Time Services

Synchronization
Mutex
Cond Var
Counting Semaphore
Xenomai Native API Synchronisation tools

Messages and Communication

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 72 / 104


Synchronization Xenomai Native API Synchronisation tools

API Mutexes

int rt_mutex_create (RT_MUTEX *mutex, const char *name)


int rt_mutex_acquire (RT_MUTEX *mutex, RTIME timeout)
int rt_mutex_release (RT_MUTEX *mutex)

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 73 / 104


Synchronization Xenomai Native API Synchronisation tools

API Condition variables

int rt_cond_create (RT_COND *cond, const char *name)


int rt_cond_signal (RT_COND *cond)
int rt_cond_broadcast (RT_COND *cond)
int rt_cond_wait (RT_COND *cond, RT_MUTEX *mutex, RTIME timeout)

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 74 / 104


Synchronization Xenomai Native API Synchronisation tools

API Counting Semaphores

int rt_sem_create (RT_SEM *sem, const char *name,


unsigned long icount, int mode)
int rt_sem_p (RT_SEM *sem, RTIME timeout)
int rt_sem_v (RT_SEM *sem)
int rt_sem_broadcast (RT_SEM *sem)

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 75 / 104


Messages and Communication Signals

Layout

Scheduling

Management

Time Services

Synchronization

Messages and Communication


Signals
Mail Queue
Xenomai Native API

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 76 / 104


Messages and Communication Signals

Real-Time Signals

Signal : event delivered in asynchronous way to a process/thread (software


interruption).
I Blocked signals (or masked) pending or delivered.
I Default behaviour can be modied by user.
I One signal register for each thread/process.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 77 / 104


Messages and Communication Signals

Real-Time Signals

Existing mechanism in POSIX.1 but with the following issues :


I Implementation pending signal register = unsafe delivery (possible
loss).
I Emitting order not respected when they are delivered.
I Does not contain many information and few of them are available for
user : not adapted to IPC implementation.
I Not ecient (slow : high latency).

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 78 / 104


Messages and Communication Signals

Real-Time Signals : POSIX Interface

kill Emission of a signal.


sigaction Connection of a handler to a signal.
sigemptyset Initialize with all signals disabled.(mask all signals)
sigllset Initialize with all signals enabled.(unmask all signals)
sigaddset Add a signal in the set(unmask this signal).
sigdelset Remove a signal from the set(mask this signal).
sigismember Check if the signal is enabled in the set.
sigsuspend Block a process until a signal is received.
sigprocmask Install a mask.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 79 / 104


Messages and Communication Signals

Signals : Non RT Example

void handler ( int sig ){


printf (" Signal % d received \ n " , sig );}

int main ( int argc , char * argv []){


struct sigaction sig ;
sig . sa_flags = SA_RESTART ;
sig . sa_handler = handler ;
sigemptyset (& sig . sa_mask );
sigaction ( SIGUSR1 ,& sig , NULL );
while (1); // program computes !!
}

Execution :
$sig &
$kill - USR1 14090
Signal 10 received

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 80 / 104


Messages and Communication Signals

Real-Time signals : POSIX Extended

Range of new signals numbered from SIGRTMIN to SIGRTMAX (that


represent a minimum of RTSIG_MAX signals)
I Possibility to use a value linked to this signal.
I No loss of signal : using of a queue for pending signals.
I Ordered delivery : respecting scheduling policy chosen + priority
linked to a signal ⇒ SIGRTMIN has the highest priority.
I Emitted with a kill, sigqueue, with a timer or by an asynchronous IO.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 81 / 104


Messages and Communication Signals

Real-Time Signals : POSIX Extended

Complementary interfaces of POSIX.4 :


sigqueue Emit a real-time signal.
sigwaitinfo Wait for a signal without handler execution
sigtimedwait Idem above + timeout on blocking time.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 82 / 104


Messages and Communication Signals

Real-Time Signals : RT Example

int main ( int argc , char * argv []){


struct sigaction sig ;
union sigval val ;
int cpt ;
sig . sa_flags = SA_SIGINFO ;
sig . sa_sigaction = handler ;
sigemptyset (& sig . sa_mask );
if ( sigaction ( SIGRTMIN ,& sig , NULL ) <0)
perror (" sigaction ");
for ( cpt =0; cpt <5; cpt ++){
struct timespec delai ;
delai . tv_sec =1; delai . tv_nsec =0;
val . sival_int = cpt ;
sigqueue (0 , SIGRTMIN , val );
nanosleep (& delai , NULL );
}
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 83 / 104


Messages and Communication Signals

RealTime Signals : RT Example

void handler ( int sig , siginfo_t * sip , void * uap )


{
printf (" Received signal %d , val = % d \ n " ,
sig , sip - > si_value . sival_int );
}

Execution :

\ $rt - sig
Received signal 38 , val = 0
Received signal 38 , val = 1
Received signal 38 , val = 2
Received signal 38 , val = 3
Received signal 38 , val = 4

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 84 / 104


Messages and Communication Mail Queue

Layout

Scheduling

Management

Time Services

Synchronization

Messages and Communication


Signals
Mail Queue
Xenomai Native API

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 85 / 104


Messages and Communication Mail Queue

Mechanism

With UNIX, Communication mechanism is the pipeline (named or not) ⇒


too abstract for real-time constraints.
Mail queues in POSIX.4 have the same features :
I Priority in emission/reception.
I Can work in Non-blocking
I Can preallocate resources.
I Can communicate in Inter-Process and Inter-Thread mode.
I Unfortunately, priority inversion issues are not addressed.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 86 / 104


Messages and Communication Mail Queue

API

mq_open Creation or connection to a queue.


mq_unlink Destruction of a queue.
mq_receive Reception of the oldest and the most important
mail.
mq_send Emission of a mail with a given priority
mq_close Disconnection to a queue.
mq_notify Notication that there is a new mail.
mq_setattr Set attributes of the queue.
mq_getattr Get attributes of the queue.

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 87 / 104


Messages and Communication Mail Queue

Example

/* Emission with a priority 1 ( from 0 to


MQ_PRIO_MAX ) */
mq_send ( id , buff ,100 ,1);
pthread_create (& tid , NULL , consumer , NULL );
pthread_exit ( NULL );
}

void * consumer ( void * arg ){


mqd_t id ;
char buff [100];
id = mq_open ("/ myqueue " , O_RDONLY );
mq_receive ( id , buff ,100 , NULL );
printf (" msg = % s \ n ", buff );
mq_unlink ("/ myqueue ");
pthread_exit ( NULL );
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 88 / 104


Messages and Communication Mail Queue

Example

# include < pthread .h >


# include < mqueue .h >
int main ( int argc , char * argv [])
{
pthread_t tid ;
mqd_t id ;
char buff [100];
struct mq_attr attr ;
attr . mq_maxmsg =100;
attr . mq_flags =0;
attr . mq_msgsize =100;
id = mq_open ("/ mafile " , O_CREAT | O_WRONLY ,
444 ,& attr );
strcpy ( buff ," Hi !!");
...
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 89 / 104


Messages and Communication Xenomai Native API

Layout

Scheduling

Management

Time Services

Synchronization

Messages and Communication


Signals
Mail Queue
Xenomai Native API

IO Control

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 90 / 104


Messages and Communication Xenomai Native API

API Event ags groups

I Synchronizing object based on a long word structure.


I Any bit in the word can be used as a user ag
I Task oriented signal mechanism
I Conjunctive or Disjunctive

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 91 / 104


Messages and Communication Xenomai Native API

API Event ags groups

int rt_event_create (RT_EVENT *event, const char *name,


unsigned long ivalue, int mode)
int rt_event_signal (RT_EVENT *event, unsigned long mask)
int rt_event_wait (RT_EVENT *event, unsigned long mask,
unsigned long *mask_r, int mode, RTIME timeout)
int rt_event_clear (RT_EVENT *event, unsigned long mask,
unsigned long *mask_r)

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 92 / 104


Messages and Communication Xenomai Native API

API Messages queue

int rt_queue_create (RT_QUEUE *q, const char *name,


size_t poolsize, size_t qlimit, int mode)
void * rt_queue_alloc (RT_QUEUE *q, size_t size)
int rt_queue_free (RT_QUEUE *q, void *buf)
int rt_queue_send (RT_QUEUE *q, void *mbuf, size_t size, int mode)
int rt_queue_write (RT_QUEUE *q, const void *buf, size_t size, int mode)
ssize_t rt_queue_receive (RT_QUEUE *q, void **bufp, RTIME timeout)
ssize_t rt_queue_read (RT_QUEUE *q, void *buf, size_t size, RTIME timeout)

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 93 / 104


Messages and Communication Xenomai Native API

API Messages pipe

int rt_pipe_create (RT_PIPE *pipe, const char *name,


int minor, size_t poolsize)
ssize_t rt_pipe_receive (RT_PIPE *pipe,
RT_PIPE_MSG **msgp, RTIME timeout)
ssize_t rt_pipe_read (RT_PIPE *pipe, void *buf, size_t size, RTIME timeou
ssize_t rt_pipe_send (RT_PIPE *pipe, RT_PIPE_MSG *msg,
size_t size, int mode)
ssize_t rt_pipe_write (RT_PIPE *pipe, const void *buf, size_t size,
int mode)
ssize_t rt_pipe_stream (RT_PIPE *pipe, const void *buf, size_t size)
RT_PIPE_MSG * rt_pipe_alloc (RT_PIPE *pipe, size_t size)
int rt_pipe_free (RT_PIPE *pipe, RT_PIPE_MSG *msg)
int rt_pipe_ush (RT_PIPE *pipe, int mode)

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 94 / 104


Messages and Communication Xenomai Native API

Example : Pipe Kernel side


# include < sys / types .h >
# include < fcntl .h >
# include < string .h >
# include < stdio .h >
# include < native / pipe .h >
# define TASK_PRIO 0 /* Highest RT priority */
# define TASK_MODE T_FPU | T_CPU (0) /* Uses FPU , bound to CPU #0 *
# define TASK_STKSZ 4096 /* Stack size ( in bytes ) */

RT_TASK task_desc ;
RT_PIPE pipe_desc ;

void task_body ( void ){


RT_PIPE_MSG * msgout , * msgin ;
int err , len , n ;
for (;;) {
/* ... */
len = sizeof (" Hello ");
/* Get a message block of the right size in order to
initiate the message - oriented dialog with the
Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 95 / 104
Messages and Communication Xenomai Native API

Example : Pipe Kernel side

# include < native / pipe .h >


RT_PIPE pipe_desc ;
int init_module ( void )
{
int err ;
/* Connect the kernel - side of the message pipe to the
special device file / dev / rtp7 . */
err = rt_pipe_create (& pipe_desc ," MyPipe " ,7 , NULL );
...
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 96 / 104


Messages and Communication Xenomai Native API

Example : Pipe User side

From a regular Linux process :


# include < native / pipe .h >
int pipe_fd ;
int main ( int argc , char * argv [])
{
/* Open the Linux side of the pipe . */
pipe_fd = open ("/ dev / rtp7 " , O_RDWR );
/* ou grace au service de registres */
pipe_fd = open ("/ proc / xenomai / registry / native / pipes / MyPipe " , O_R
...
/* Write a message to the pipe . */
write ( pipe_fd ," hello world " ,11);
...
}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 97 / 104


IO Control Memory

Layout

Scheduling

Management

Time Services

Synchronization

Messages and Communication

IO Control
Memory
Control I/O

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 98 / 104


IO Control Memory

Management

A shared time system leads to possible time indeterminism because :


I Dynamic memory allocation.
I Page swap : swapin=swapout.

Solution : limit dynamic memory allocation and lock pages in central


memory (POSIX.4 Interface) :
I mlockall()=munlockall() : lock/unlock swap with all memory pages of
this process..
I mlock()=munlock() : lock/unlock a range of addresses.

! Warning : mlock() is not portable (because there is no memory model in


POSIX standard).

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 99 / 104


IO Control Memory

API Memory heap

int rt_heap_create (RT_HEAP *heap, const char *name, size_t heapsize, int mode)
int rt_heap_alloc (RT_HEAP *heap, size_t size, RTIME timeout, void **blockp)
int rt_heap_free (RT_HEAP *heap, void *block)

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 100 / 104
IO Control Control I/O

Layout

Scheduling

Management

Time Services

Synchronization

Messages and Communication

IO Control
Memory
Control I/O

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 101 / 104
IO Control Control I/O

API Interrupt management

int rt_intr_create (RT_INTR *intr, const char *name, unsigned irq,


rt_isr_t isr, rt_iack_t iack, int mode)[Kernel]
int rt_intr_create (RT_INTR *intr, const char *name, unsigned irq, int mode)[User]
int rt_intr_enable (RT_INTR *intr)
int rt_intr_disable (RT_INTR *intr)
int rt_intr_wait (RT_INTR *intr, RTIME timeout)

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 102 / 104
IO Control Control I/O

Example : User Interruption


# include < sys / mman .h >
# include < native / task .h >
# include < native / intr .h >

# define IRQ_NUMBER 7 /* Intercept interrupt #7 */


# define TASK_PRIO 99 /* Highest RT priority */
# define TASK_MODE 0 /* No flags */
# define TASK_STKSZ 0 /* Stack size ( use default one ) */

RT_INTR intr_desc ;
RT_TASK server_desc ;

void irq_server ( void * cookie ){


for (;;) {
/* Wait for the next interrupt on channel #7. */
err = rt_intr_wait (& intr_desc , TM_INFINITE );
if (! err ) {
/* Process interrupt . */
}
}
Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 103 / 104
IO Control Control I/O

Example : User Interruption

int main ( int argc , char * argv []){


int err ;
mlockall ( MCL_CURRENT | MCL_FUTURE );
/* ... */
err = rt_intr_create (& intr_desc ," MyIrq " , IRQ_NUMBER ,0);
/* ... */
err = rt_task_create (& server_desc ,
" MyIrqServer " ,
TASK_STKSZ ,
TASK_PRIO ,
TASK_MODE );
if (! err )
rt_task_start (& server_desc ,& irq_server , NULL );
/* ... */
}
void cleanup ( void ){
rt_intr_delete (& intr_desc );
rt_task_delete (& server_desc );}

Ludovic Saint-Bauzel (Polytech'Pqris UPMC) OS : Tasks And Threads 2011-2012 104 / 104

You might also like