11/6/17

Thread and multitasking

Alberto Bosio, Associate Professor – UM Microelectronic Departement [email protected]

Agenda

l POSIX Threads Programming l http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html

l Compiler: http://cygwin.com/index.html

1 11/6/17

Process vs

thread

Picture source: https://computing.llnl.gov/tutorials/pthreads/

Shared Memory Model

Picture source: https://computing.llnl.gov/tutorials/pthreads/

2 11/6/17

Simple Thread Example void *func ( ) { /* define local data */ ------/* function code */ ------pthread_exit(exit_value); } int main ( ) { pthread_t tid; int exit_value; ------pthread_create (0, 0, func (), 0); ------pthread_join (tid, &exit_value); ------}

Basic Functions

Purpose Process Model Threads Model

Creation of a new thread ( ) thr_create( )

Start execution of a new thread exec( ) [ thr_create() builds the new thread and starts the execution

Wait for completion of thread wait( ) thr_join()

Exit and destroy the thread exit( ) thr_exit()

3 11/6/17

Code comparison

main ( ) main() { { fork ( ); thread_create(0,0,func(),0); fork ( ); thread_create(0,0,func(),0); fork ( ); thread_create(0,0,func(),0); } }

Creation

#include int pthread_create( pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);

4 11/6/17

Exit

#include

void pthread_exit(void *retval);

join

#include int pthread_join( pthread_t thread, void *retval);

5 11/6/17

Joining

Passing argument (wrong example) int rc; long t; for(t=0; t

6 11/6/17

Passing argument (good example) long *taskids[NUM_THREADS]; for(t=0; t

Exercise

l Look the program Ex1.

l What is the error?

l Correct it. l Write a C program able to parallelize the matrix multiplication

l Given M1[M][N] and M2[N][P]

l Calculate MR[M][P]

7 11/6/17

Problems

l What happens in case of dependencies?

l A=B;

l B=C;

Resource

l Definition

l What a task need to be executed. - Hardware (device) - Software (variable)

l The resource is characterized by - Its state : availbale/unavailbe - The access point number

8 11/6/17

Resources

l Protocol to use a resource

l 3 steps: - Allocation, Utilization, Restitution

l They ensure that the resource is used as specified by the point access number - Critical ressource has only one access point

The

Structure

P (Sem) Queue L

V (Sem) Counter K (smepahore state) Val Sem INIT (Val, Sem)

Atomic operations

9 11/6/17

The semaphore

l A useful way to think of a semaphore is as a record of how many units of a particular resource are available

n INIT (Sem, Val) initializes the number of units

n P(Sem) gives a unit to the task. If no more units are available it stops the task and put it in to the queue Sem.L

n V(Sem) takes a unit and wake up one task from Sem.L if any.

The semaphore

Init (Val, Sem)

begin mask_it Sem. K := Val; Sem. L := NULL ; unmask_it end

10 11/6/17

The semaphore

P (Sem) Sleep

begin mask_it Sem.K := Sem.K - 1; If Sem.K < 0 then add task to Sem.L < 0 task sleep endif unmask_it end

The semaphore

Wake up

V (Sem) begin mask_it Sem.K := Sem.K + 1; If Sem.K <= 0 then dequeue a task from Sem.L <= 0 wake up the task Endif unmask_it end

11 11/6/17

The semaphore

l If Sem.K <= 0, then the absolute_value(Sem.K) is the number of sleeping tasks in the queue.

P3 P4 P1

P(Sem) P3P4

K = -1 P(Sem) Sleep V(Sem) -2 K = -2 Sleep K = -1 Wake up P3

The semaphore

l Meaning of counter K

l if Sem.K > 0, Sem.K corresponds to the number of non-blocking P

P1 P2 P3

P(Sem)

K = 1 P(Sem) P(Sem) 2 K = 0 K < 0 Sleep

12 11/6/17

Critical Section

1 task in the critical section => 1 unit Semaphore Mutex initiliazed to 1

P (Mutex) Enter the critical section

Critical Section

V (Mutex) Exit the critical section

Classical Scheme Producer - Consumer

Circle Buffer

Produced Consumer

13 11/6/17

Classical Scheme Producer - Consumer Buffer of N messages

Consumer Producer

Full places resource Empty places resource 0 N Empty Semaphore Full Sempahore

Empty Semaphore: Init (Vide, N) Full Semaphore: Init (Plein, 0)

n Producer n Consumer index i: = 0 index j:= 0

P(Full) P(Empty) message:= T(j); T(i):=message; i : = i + 1 mod N; j : = j + 1 mod N; V(Full) V(Empty)

14 11/6/17

Mutex

l Mutex is an abbreviation for "mutual exclusion” l pthread_mutex_init (mutex,attr) l pthread_mutex_destroy (mutex) l pthread_mutex_lock (mutex) l pthread_mutex_trylock (mutex) l pthread_mutex_unlock (mutex)

Condition Variables

l Condition variables provide yet another way for threads to synchronize. While mutexes implement synchronization by controlling thread access to data, condition variables allow threads to synchronize based upon the actual value of data.

l Without condition variables, the programmer would need to have threads continually polling (possibly in a critical section), to check if the condition is met. This can be very resource consuming since the thread would be continuously busy in this activity. A condition variable is a way to achieve the same goal without polling.

l A condition variable is always used in conjunction with a mutex .

15 11/6/17

Condition variables

l pthread_cond_init (condition,attr)

l pthread_cond_destroy (condition)

31

Condition variables

l pthread_cond_wait (condition,mutex)

l blocks the calling thread until the specified condition is signalled.

l This routine should be called while mutex is locked, and it will automatically release the mutex while it waits. After signal is received and thread is awakened, mutex will be automatically locked for use by the thread. The programmer is then responsible for unlocking mutex when the thread is finished with it.

16 11/6/17

Condition variables

l pthread_cond_signal (condition)

l routine is used to signal (or wake up) another thread which is waiting on the condition variable. It should be called after mutex is locked, and must unlock mutex in order for pthread_cond_wait() routine to complete.

Condition variables

l pthread_cond_signal (condition)

l routine is used to signal (or wake up) another thread which is waiting on the condition variable. It should be called after mutex is locked, and must unlock mutex in order for pthread_cond_wait() routine to complete.

17 11/6/17

Condition variables

l pthread_cond_signal (condition)

l routine is used to signal (or wake up) another thread which is waiting on the condition variable. It should be called after mutex is locked, and must unlock mutex in order for pthread_cond_wait() routine to complete.

Thread and Semaphore

l Implement semaphore using mutex and condition variable

18 11/6/17

lExercice

Robot

M1 Stock M2 S

l There are two machines (M1 and M2) working in parallel. l M1 produces pieces, the robot allows to move a piece from M1 to the stock. l M2 gets pieces from the stock. The robot allows to move a piece from the stock to M2. l The stock S has a limited size of 4 pieces. l What are the resources ? l Write a program to simulate the behavior of this system

19