42
THREAD IMPLEMENTATION For parallel processing

THREAD IMPLEMENTATION

Embed Size (px)

DESCRIPTION

THREAD IMPLEMENTATION. For parallel processing. Steps involved. Creation Creates a thread with a thread id . Detach and Join All threads must be detached or joined with. Termination Analogous to exit. Create a Thread. pthread_create() - PowerPoint PPT Presentation

Citation preview

Page 1: THREAD  IMPLEMENTATION

THREAD IMPLEMENTATION

For parallel processing

Page 2: THREAD  IMPLEMENTATION

Steps involved

• Creation

Creates a thread with a thread id.

• Detach and Join

All threads must be detached or joined with.

• Termination

Analogous to exit

Page 3: THREAD  IMPLEMENTATION

Create a Threadpthread_create()

 

•Thread creation adds a new thread of control to the current process.

•The procedure main(), itself, is a single thread of control.

•Each thread executes simultaneously with all the other threads within the calling process, and with other threads from other active processes.  

Page 4: THREAD  IMPLEMENTATION

Functions of pthread_create()

• Creates the thread with passed parameters• Stores thread ID upon success• Returns ‘0’ on successful creation and a

non-zero value on failure; this property can be used for checking whether the thread has been at all created or not.

Page 5: THREAD  IMPLEMENTATION

The newly created thread :

• shares all of the calling process' global data with the other threads in this process; however, it has its own set of attributes and private execution stack.

• inherits the calling thread's signal mask, and scheduling priority. Pending signals for a new thread are not inherited and will be empty.

Page 6: THREAD  IMPLEMENTATION

#include <pthread.h>  int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg);

• thread - address where the Thread Identification of the newly created thread is placed.

• attr - address where the attributes the newly created thread should inherit. (if this argument is NULL, then the default attributes are inherited.)

• start_routine - contains the function with which the new thread begins execution. If start_routine returns, the thread exits with the exit status set to the value returned by start_routine.

• arg - the argument passed to start_routine. Only one argument can be passed. If more than one argument needs to be passed to start_routine, the arguments can be packed into a structure and the address of that structure can be passed to arg.

Page 7: THREAD  IMPLEMENTATION

Pitfall in pthread_create()

• arg is a pointer to data, a common mistake is to pass this parameter and then overwritten it when calling a new thread.

• You must make sure a thread will no longer access this data before overwriting it with a new value to be passed to another thread.

Page 8: THREAD  IMPLEMENTATION

  Get the Thread Identifier

• pthread_self() - Gets the ID of the calling thread.

pthread_t pthread_self( void );

• Yield Thread Execution

pthread_yield() - Causes the current thread to yield its execution in favor of another thread with the same or greater priority. 

void pthread_yield( void );

Page 9: THREAD  IMPLEMENTATION

WarningIf you create multiple threads, be careful that

there is no sharing of arguments, or that sharing is safe:

• For example: if you use same data structures for all threads and modify its fields before each call to create pthread_create(). Some threads may not be able to read the arguments desired to them.

solution: use pthread_yield() after pthread_create()• Safe way: have a separate arguments for each threadhttp://navet.ics.hawaii.edu/~casanova/courses/ics432_fall08/slides/

ics432_pthreads.pdf

Page 10: THREAD  IMPLEMENTATION

Send a Signal to a Thread

• pthread_kill() - sends a signal to a thread.

#include <sys/types.h>

#include <signal.h>

 

int kill( pid_t target, int sig );

int tkill( pid_t tid, int sig );

Page 11: THREAD  IMPLEMENTATION

• kill() sends the signal sig to the thread specified by target. target must be a process. The sig argument must be from the list given in signal.

• tkill() sends the signal sig to the thread specified by tid. tid must be a thread within the same process as the calling thread. The sig argument must be from the list given in signal. tkill() is Linux specific. Do not use tkill() if you plan on making your program portable.

Page 12: THREAD  IMPLEMENTATION

Terminate a Thread • The thread returns from its start routine.

• pthread_exit() - terminates a thread. void pthread_exit( void *status ); • The pthread_exit() function terminates the calling thread. All

thread-specific data bindings are released.

• If the calling thread is not detached, the thread's ID and the exit status specified by status are retained until the thread is waited for.

• Otherwise, status is ignored and the thread's ID can be reclaimed immediately.

Page 13: THREAD  IMPLEMENTATION

Wait for Thread Termination

• pthread_join() - waits for a thread to terminate. 

int pthread_join( pthread_t wait_for, void **status );

• The pthread_join() function blocks the calling thread until the thread specified by wait_for terminates. The specified thread must be in the current process and must not be detached.

• When status is not NULL, it points to a location that is set to the exit status of the terminated thread when pthread_join() returns successfully.

 

Page 14: THREAD  IMPLEMENTATION

pthread_join()

https://computing.llnl.gov/tutorials/pthreads/#Abstract

Page 15: THREAD  IMPLEMENTATION

Related Functions•  thr_sigsetmask() – accesses the signal mask of the calling

thread

• pthread_key_create(), thr_setspecific(), thr_getspecific() - maintain thread-specific data

• thr_getconcurrency(), thr_setconcurrency() - get and set thread concurrency level

(Concurrency: Many threads could be operating concurrently, on a

multi threaded kernel.)

• thr_getprio(), thr_setprio() - get and set thread priority

Page 16: THREAD  IMPLEMENTATION

Programming with Synchronization use Mutex

For protecting critical areas of code

Page 17: THREAD  IMPLEMENTATION

Create a mutex

• Initializes a static mutex with default attributes.

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER

• The PTHREAD_MUTEX_INITIALIZER macro initializes the static mutex mutex, setting its attributes to default values. This macro should only be used for static mutexes, as no error checking is performed.

Page 18: THREAD  IMPLEMENTATION

Lock a mutex

pthread_mutex_lock()  int pthead_mutex_lock( pthread_mutex_t *mp );

Use pthead_mutex_lock() to lock the mutex pointed by mp. When themutex is already locked, the calling thread blocks until the mutexbecomes available (blocked threads wait on a prioritized queue). Whenpthread_mutex_lock() returns, the mutex is locked and the callingthread is the owner.

Page 19: THREAD  IMPLEMENTATION

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

if( condition holds) { pthread_mutex_lock( &mutex1 );{\\ CRITICAL SECTION}

pthread_mutex_unlock( &mutex1 ); }

Page 20: THREAD  IMPLEMENTATION

Lock with a Nonblocking Mutex

int pthread_mutex_trylock( pthread_mutex_t *mp);

 • Use pthread_mutex_trylock() to attempt to

lock the mutex pointed to by mp. This function is a non-blocking version of pthread_mutex_lock(). When the mutex is already locked, this call returns with an error. Otherwise, the mutex is locked and the calling thread is the owner.

Page 21: THREAD  IMPLEMENTATION

Unlock a Mutex

int pthread_mutex_unlock( pthread_mutex_t *mp);

• Use the pthread_mutex_unlock() to unlock the mutex pointed to by mp.

• The mutex must be locked and the calling thread must be the one that last locked the mutex (the owner).

Page 22: THREAD  IMPLEMENTATION

Related Functions

• pthead_mutex_init() – dynamically initializes a mutual exclusion lock

• pthread_mutex_destroy() - destroys mutex state

Page 23: THREAD  IMPLEMENTATION

Condition Variables

• Use condition variables to atomically block threads until a particular condition is true.

• Always use condition variables together with a mutex lock.

pthread_mutex_lock();

while( condition_is_false )

pthread_cond_wait();

pthread_mutex_unlock();

Page 24: THREAD  IMPLEMENTATION

Block on a Condition Variable

 int pthread_cond_wait( pthread_cond_t *cvp, pthread_mutex_t *mp );

 

• Use pthread_cond_wait() to atomically release the mutex

pointed by mp and to cause the calling thread to block

on the condition variable pointed to by cvp.

• The blocked thread can be awakened by

pthread_cond_signal(), pthread_cond_broadcast(), or

when interrupted by delivery of a signal. 

Page 25: THREAD  IMPLEMENTATION

Unblock a Specific Thread

int pthread_cond_signal( pthread_cond_t *cvp ); 

• Use pthread_cond_signal() to unblock one thread that is blocked on the condition variable pointed to by cvp. Call pthread_cond_signal() under the protection of the same mutex used with the condition variable being signaled.

• When no threads are blocked on the condition variable, the pthread_cond_signal() has no effect.

Page 26: THREAD  IMPLEMENTATION

Related Functions

• pthread_cond_init() - initializes a condition variable

• pthread_cond_timedwait() - blocks until a specified event

• pthread_cond_broadcast() - unblocks all threads

• pthread_cond_destroy() - destroys condition variable state

Page 27: THREAD  IMPLEMENTATION

ASSIGNMENT 2 Mutual Exclusion

Page 28: THREAD  IMPLEMENTATION

PROBLEM STATEMENTYour assignment is to create a banking system, with threads that simulate the Sanders family accessing two accounts(checking and savings). The Sanders family consists of three people:  Bruce Sanders(the father), a freewheeling biker who is gone for long periods of time on drinking binges but who also holds the patents on a large number of devices like hooks, suction cups, and glass. He spends a lot and makes a lot. Jennifer Sanders(the mother), a home maker who doesn't contribute anything but only takes a very small amount at a time, she also keeps track of the finances and makes sure there's enough money in the savings account. Jill Sanders(the daughter), who is away at college and therefore constantly drains financial resources.

Page 29: THREAD  IMPLEMENTATION

INPUT

• The text file inputs are available on:http://web.mst.edu/~ercal/284/Asg-2/asg2-father.txt

, http://web.mst.edu/~ercal/284/Asg-2/asg2-mother.txt

http://web.mst.edu/~ercal/284/Asg-2/asg2-daughter.txt

• Each file describe the usage pattern of each

user. Pattern of entry in input file are:Character Account Amount ( example: d/w/t 0/1 50)

Page 30: THREAD  IMPLEMENTATION

COMPONENTS OF THE SOLUTION APPROACH

1) TWO DIFFERENT ACCOUNTS – CHECKING AND SAVING (global variables)

2) MAIN FUNCTION3) DIFFERENT THREADS FOR DIFFERENT

USERS4) START ROUTINE WHICH WILL SIMULATE THE

OPERATIONS TO BE DONE BY EACH THREAD

5) THREE DIFFERENT OPERATIONS ON EACH ACCOUNT (DEPOSIT, WITHDRAWAL, TRANSFER)

6) MUTEX LOCKS ON EACH ACCOUNT

Page 31: THREAD  IMPLEMENTATION

TWO DIFFERENT ACCOUNTS – CHECKING AND SAVING

• Denoted by two different notations

• Two global variables to be protected

• Needs two different mutex locks

• Initial balance is zero

• Three different operations on each account is allowed

Page 32: THREAD  IMPLEMENTATION

MAIN FUNCTION

• Create three threads using pthread_create() to simulate father, mother and daughter

• Join each thread using pthread_join() to wait for each thread’s termination

Page 33: THREAD  IMPLEMENTATION

Passing Multiple Arguments

• Each Thread has its id and file:

To pass the data like threadID, inputfile etc, a structure can be implemented holdingthreadID and corresponding inputfile.

FOR EXAMPLE-struct Eg{

mem1 (inputfile)mem2 – number

};

Main(){Eg THREADi;THREADi.inputfile = arg[i];THREADi.number = I;}

http://web.mst.edu/~ercal/284/ThreadExamples/passingthingstothreads.txt

Page 34: THREAD  IMPLEMENTATION

DIFFERENT THREADS FOR DIFFERENT USERS

• pthread_create( &threadid, NULL, startroutine, (void *)&THREADi)) )

startrountine function should read each file and perform actions encoded in the file

• Use an error checking to see whether the thread is created or not.

[USE RETURN VALUE OF pthread_create()]

• Join each thread using pthread_join() in main.

Page 35: THREAD  IMPLEMENTATION

START ROUTINE WHICH WILL SIMULATE THE OPERATIONS TO BE DONE BY EACH THREAD

• Each THREADi is passed as parameter of start_routine().

void *start_routine(void *userthread) // userthread : particular thread argument or structure for each thread

• Open (ifstream) input file

• Read entire file into a string stream

• Parse values from the string stream to variables

• while(!=EOF)

DO

{

operation first value of the entry (d/w/t)

account second value of entry (checking/saving)

amount third value of entry

CALL THE CORRESPONDING FUNCTION PASSING THE opeartion, account AND amount)

}

• usleep(random amount of time) //put thread to execute in interleaved way

Page 36: THREAD  IMPLEMENTATION

MUTEX LOCKS ON EACH ACCOUNT

• For withdraw and deposit functions, the account being operated needs to be locked by a mutex lock.

• For transfer function (between these two accounts only), both the accounts need to be locked by mutex locks.Pay attention to Deadlock: if one lock has been obtained in a thread other than transfer, then a deadlock happens.

Page 37: THREAD  IMPLEMENTATION

EXAMPLEDEPOSIT FUNCTION: ONLY ONE LOCK FOR CHECKING OR SAVING

if(account is CHECKING) { pthread_mutex_lock( &mutex_checking );

\\ CRITICAL SECTIONINCREASE BALANCE IN ACCOUNT AND PRINT STATEMENT

pthread_mutex_unlock( &mutex_checking ); } else { pthread_mutex_lock( &mutex_saving );

\\ CRITICAL SECTIONINCREASE BALANCE IN ACCOUNT AND PRINT STATEMENT

pthread_mutex_unlock( &mutex_saving ); }

Page 38: THREAD  IMPLEMENTATION

TRANSFER FUNCTION: TWO LOCKS FOR CHECKING AND SAVINGPAY ATTENTION TO THE ORDER OF LOCK AND UNLOCK OF TWO

ACCOUNTS

if(account is CHECKING) { pthread_mutex_lock( &mutex_checking );

pthread_mutex_lock( &mutex_saving );\\ CRITICAL SECTIONTRANSFER BALANCE BETWEEN CHECKING ACCOUNT AND

SAVING ACCOUNT AND PRINT STATEMENT

pthread_mutex_unlock( &mutex_saving );pthread_mutex_unlock( &mutex_checking );

}

Page 39: THREAD  IMPLEMENTATION

Withdraw / Overdraw logic

• if(w from checking and wamount > checkingbalance) get money from savings to cover it (initiate a transfer)

• if(w or t from saving and wamount > savingsbalance and savingsbalance is +) allow balance to go negative.

• if(w or t from saving and savingsbalance is -) deny action, print warning

• if(t from checking and wamount > checkingbalance and checkingbalance > 0) allow balance to go negative, print warning.

• if(t from checking and checkingbalance <0 ) deny action, print warning

Page 40: THREAD  IMPLEMENTATION

Useful Information

• When the user deposits, withdraws, or transfers, we should see a message to that effect. (e.g., "Bruce deposited x dollars. New balance total: y")

• Compile command:

g++ assignment2.cpp –o assignment2 –lpthread• Run command:

assignment2 filename1 filename2 filename3

Page 41: THREAD  IMPLEMENTATION

SAMPLE RUN

Command: “script mySession.txt”, after running, “exit”

[cchv5f@dell12 assignment2]$./assignment2 father daughter mother Jennifer:You do not have 37 dollars in checking to transfer.Bruce:14 dollars deposited in savings. New Balance: 14Jill:Withdrawal of 30 failed. You only have 14 dollars available in savings.Jennifer:14 dollars has been transferred from savings to checking.Jennifer:You do not have 49 dollars in savings to transfer.Bruce:14 dollars deposited in checking. New balance: 28Bruce:32 dollars deposited in checking. New balance: 60Jill:Withdrawal of 13 successful. 47 dollars remain in your checking

account.User 2:33 dollars has been transferred from checking to savings.

Jill:Withdrawal of 5 successful. 28 dollars remain in your savings account.Jennifer:10 dollars has been transferred from checking to savings.

Page 42: THREAD  IMPLEMENTATION

Questions?THANK YOU