Asg2 Thread Supp

Embed Size (px)

Citation preview

  • 8/2/2019 Asg2 Thread Supp

    1/42

    THREAD

    IMPLEMENTATION

    For parallel processing

  • 8/2/2019 Asg2 Thread Supp

    2/42

    Steps involved

    Creation

    Creates a thread with a thread id.

    Detach and Join

    All threads must be detached or joinedwith.

    Termination

    Analogous to exit

  • 8/2/2019 Asg2 Thread Supp

    3/42

    Create a Threadpthread_create()

    Thread creation adds a new thread of controlto the current process.

    The procedure main(), itself, is a singlethread of control.

    Each thread executes simultaneously with allthe other threads within the calling process,and with other threads from other activeprocesses.

  • 8/2/2019 Asg2 Thread Supp

    4/42

    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 propertycan be used for checking whether thethread has been at all created or not.

  • 8/2/2019 Asg2 Thread Supp

    5/42

    The newly created thread :

    shares all of the calling process' globaldata with the other threads in this process;however, it has its own set of attributesand private execution stack.

    inherits the calling thread's signal mask,and scheduling priority. Pending signalsfor a new thread are not inherited and willbe empty.

  • 8/2/2019 Asg2 Thread Supp

    6/42

    #include

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

    thread- address where the Thread Identification of the newlycreated thread is placed.

    attr- address where the attributes the newly created thread shouldinherit. (if this argument is NULL, then the default attributes areinherited.)

    start_routine- contains the function with which the new threadbegins execution. If start_routinereturns, 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 canbe passed. If more than one argument needs to be passed tostart_routine, the arguments can be packed into a structure and the

    address of that structure can be passed to arg.

  • 8/2/2019 Asg2 Thread Supp

    7/42

    Pitfall in pthread_create()

    arg is a pointer to data, a commonmistake is to pass this parameter and

    then overwritten it when calling a newthread.

    You must make sure a thread will no

    longer access this data beforeoverwriting it with a new value to bepassed to another thread.

  • 8/2/2019 Asg2 Thread Supp

    8/42

    Get the Thread Identifier

    pthread_self() - Gets the ID of the callingthread.

    pthread_t pthread_self( void ); Yield Thread Execution

    pthread_yield() - Causes the current

    thread to yield its execution in favor ofanother thread with the same or greaterpriority.

    void pthread_yield( void );

  • 8/2/2019 Asg2 Thread Supp

    9/42

    WarningIf you create multiple threads, be careful

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

    For example: if you use same data structures for allthreads and modify its fields before each call tocreate pthread_create(). Some threads may not beable 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

  • 8/2/2019 Asg2 Thread Supp

    10/42

    Send a Signal to a Thread

    pthread_kill() - sends a signal to a thread.

    #include

    #include

    int kill( pid_t target, int sig);

    int tkill( pid_t tid, int sig );

  • 8/2/2019 Asg2 Thread Supp

    11/42

    kill() sends the signal sigto the thread specified by

    target. targetmust be a process. The sigargumentmust be from the list given in signal.

    tkill() sends the signal sigto the thread specified

    by tid. tidmust be a thread within the sameprocess as the calling thread. The sigargumentmust be from the list given in signal. tkill() is Linuxspecific. Do not use tkill() if you plan on making

    your program portable.

  • 8/2/2019 Asg2 Thread Supp

    12/42

    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 andthe exit status specified by statusare retained until thethread is waited for.

    Otherwise, statusis ignored and the thread's ID can bereclaimed immediately.

  • 8/2/2019 Asg2 Thread Supp

    13/42

    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 untilthe thread specified by wait_forterminates. Thespecified thread must be in the current process and mustnot be detached.

    When statusis not NULL, it points to a location that isset to the exit status of the terminated thread whenpthread_join() returns successfully.

  • 8/2/2019 Asg2 Thread Supp

    14/42

    pthread_join()

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

  • 8/2/2019 Asg2 Thread Supp

    15/42

    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 setthread concurrency level

    (Concurrency: Many threads could be operating concurrently, on amulti threaded kernel.)

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

  • 8/2/2019 Asg2 Thread Supp

    16/42

    Programming with

    Synchronization use Mutex

    For protecting critical areas of code

  • 8/2/2019 Asg2 Thread Supp

    17/42

    Create a mutex

    Initializes a static mutex with default attributes.

    pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER

    The PTHREAD_MUTEX_INITIALIZER macroinitializes the static mutex mutex, setting its

    attributes to default values. This macro shouldonly be used for static mutexes, as no errorchecking is performed.

  • 8/2/2019 Asg2 Thread Supp

    18/42

    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.

  • 8/2/2019 Asg2 Thread Supp

    19/42

    pthread_mutex_t mutex1 =

    PTHREAD_MUTEX_INITIALIZER;

    if( condition holds){

    pthread_mutex_lock( &mutex1 );{\\ CRITICAL SECTION}

    pthread_mutex_unlock( &mutex1 );}

  • 8/2/2019 Asg2 Thread Supp

    20/42

    Lock with a Nonblocking Mutex

    int pthread_mutex_trylock( pthread_mutex_t*mp);

    Use pthread_mutex_trylock() to attempt tolock the mutex pointed to by mp. Thisfunction is a non-blocking version ofpthread_mutex_lock(). When the mutex isalready locked, this call returns with anerror. Otherwise, the mutex is locked andthe calling thread is the owner.

  • 8/2/2019 Asg2 Thread Supp

    21/42

    Unlock a Mutex

    int pthread_mutex_unlock( pthread_mutex_t*mp);

    Use the pthread_mutex_unlock() to unlockthe mutex pointed to by mp.

    The mutex must be locked and the callingthread must be the one that last locked themutex (the owner).

  • 8/2/2019 Asg2 Thread Supp

    22/42

    Related Functions

    pthead_mutex_init() dynamically

    initializes a mutual exclusion lock

    pthread_mutex_destroy() - destroysmutex state

  • 8/2/2019 Asg2 Thread Supp

    23/42

    Condition Variables

    Use condition variables to atomically blockthreads until a particular condition is true.

    Always use condition variables togetherwith a mutex lock.

    pthread_mutex_lock();

    while( condition_is_false )pthread_cond_wait();

    pthread_mutex_unlock();

  • 8/2/2019 Asg2 Thread Supp

    24/42

    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 mpand 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.

  • 8/2/2019 Asg2 Thread Supp

    25/42

    Unblock a Specific Thread

    int pthread_cond_signal( pthread_cond_t *cvp);

    Use pthread_cond_signal() to unblock one threadthat is blocked on the condition variable pointed to

    by cvp. Call pthread_cond_signal() under theprotection of the same mutex used with thecondition variable being signaled.

    When no threads are blocked on the conditionvariable, the pthread_cond_signal() has no effect.

  • 8/2/2019 Asg2 Thread Supp

    26/42

    Related Functions

    pthread_cond_init() - initializes acondition variable

    pthread_cond_timedwait() - blocks untila specified event

    pthread_cond_broadcast() - unblocks all

    threads pthread_cond_destroy() - destroys

    condition variable state

  • 8/2/2019 Asg2 Thread Supp

    27/42

    ASSIGNMENT 2

    Mutual Exclusion

    O S

  • 8/2/2019 Asg2 Thread Supp

    28/42

    PROBLEM STATEMENTYour assignment is to create a banking system, withthreads that simulate the Sanders family accessing twoaccounts(checking and savings). The Sanders familyconsists of three people:

    Bruce Sanders(the father), a freewheeling biker whois gone for long periods of time on drinking binges butwho also holds the patents on a large number of

    devices like hooks, suction cups, and glass. Hespends a lot and makes a lot.

    Jennifer Sanders(the mother), a home maker whodoesn't contribute anything but only takes a very smallamount at a time, she also keeps track of the finances

    and makes sure there's enough money in the savingsaccount.

    Jill Sanders(the daughter), who is away at collegeand therefore constantly drains financial resources.

  • 8/2/2019 Asg2 Thread Supp

    29/42

    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.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-

    daughter.txt

    Each file describe the usage pattern of eachuser. Pattern of entry in input file are:

    Character Account Amount

    ( example: d/w/t 0/1 50)

    http://web.mst.edu/~ercal/284/Asg-2/asg2-father.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-father.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-mother.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-mother.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-daughter.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-daughter.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-daughter.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-daughter.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-daughter.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-daughter.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-daughter.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-mother.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-mother.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-mother.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-mother.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-mother.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-father.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-father.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-father.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-father.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2-father.txt
  • 8/2/2019 Asg2 Thread Supp

    30/42

    COMPONENTS OF THE

    SOLUTION APPROACH1) TWO DIFFERENT ACCOUNTS CHECKINGAND SAVING (global variables)

    2) MAIN FUNCTION

    3) DIFFERENT THREADS FOR DIFFERENTUSERS4) START ROUTINE WHICH WILL SIMULATE THE

    OPERATIONS TO BE DONE BY EACHTHREAD

    5) THREE DIFFERENT OPERATIONS ON EACHACCOUNT (DEPOSIT, WITHDRAWAL,TRANSFER)

    6) MUTEX LOCKS ON EACH ACCOUNT

  • 8/2/2019 Asg2 Thread Supp

    31/42

    TWO DIFFERENT ACCOUNTSCHECKING 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 eachaccount is allowed

  • 8/2/2019 Asg2 Thread Supp

    32/42

    MAIN FUNCTION

    Create three threads usingpthread_create() to simulate father,

    mother and daughter Join each thread using pthread_join() to

    wait for each threads termination

  • 8/2/2019 Asg2 Thread Supp

    33/42

    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

    http://web.mst.edu/~ercal/284/ThreadExamples/passingthingstothreads.txthttp://web.mst.edu/~ercal/284/ThreadExamples/passingthingstothreads.txt
  • 8/2/2019 Asg2 Thread Supp

    34/42

    DIFFERENT THREADS FOR

    DIFFERENT USERS pthread_create( &threadid, NULL, startroutine, (void

    *)&THREADi)) )

    startrountine function should read each file andperform actions encoded in the file

    Use an error checking to see whether the thread iscreated or not.

    [USE RETURN VALUE OF pthread_create()]

    Join each thread using pthread_join() in main.

  • 8/2/2019 Asg2 Thread Supp

    35/42

    START ROUTINE WHICH WILL SIMULATE THEOPERATIONS 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

  • 8/2/2019 Asg2 Thread Supp

    36/42

    MUTEX LOCKS ON EACHACCOUNT

    For withdraw and deposit functions, theaccount 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 toDeadlock: if one lock has been obtained ina thread other than transfer, then a

    deadlock happens.

    EXAMPLE

  • 8/2/2019 Asg2 Thread Supp

    37/42

    EXAMPLE

    DEPOSIT 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 );}

  • 8/2/2019 Asg2 Thread Supp

    38/42

    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 );

    }

  • 8/2/2019 Asg2 Thread Supp

    39/42

    Withdraw / Overdraw logic

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

    if(w or t from saving and wamount > savingsbalanceand savingsbalance is +) allow balance to gonegative.

    if(w or t from saving and savingsbalance is -) denyaction, print warning

    if(t from checking and wamount > checkingbalanceand checkingbalance > 0) allow balance to gonegative, print warning.

    if(t from checking and checkingbalance

  • 8/2/2019 Asg2 Thread Supp

    40/42

    Useful Information

    When the user deposits, withdraws, or transfers, weshould see a message to that effect. (e.g., "Brucedeposited x dollars. New balance total: y")

    Compile command:

    g++ assignment2.cppo assignment2lpthread

    Run command:

    assignment2 filename1 filename2 filename3

    SAMPLE RUN

  • 8/2/2019 Asg2 Thread Supp

    41/42

    SAMPLE RUN

    Command: script mySession.txt, after running, exit

    [cchv5f@dell12 assignment2]$./assignment2 father daughter motherJennifer: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 tosavings.

    Jill:Withdrawal of 5 successful. 28 dollars remain in your savings account.

    Jennifer:10 dollars has been transferred from checking to savings.

  • 8/2/2019 Asg2 Thread Supp

    42/42

    Questions?

    THANK YOU