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

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

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.

• inherits the calling thread's signal mask. however. . it has its own set of attributes and private execution stack. Pending signals for a new thread are not inherited and will be empty.The newly created thread : • shares all of the calling process' global data with the other threads in this process. and scheduling priority.

contains the function with which the new thread begins execution. void * arg).h> int pthread_create(pthread_t * thread. If more than one argument needs to be passed to start_routine.#include <pthread.address where the Thread Identification of the newly created thread is placed.) • start_routine .address where the attributes the newly created thread should inherit. the thread exits with the exit status set to the value returned by start_routine. • attr . Only one argument can be passed. If start_routine returns. pthread_attr_t * attr. • arg . void * (*start_routine)(void *). . then the default attributes are inherited. (if this argument is NULL.the argument passed to start_routine. • thread . the arguments can be packed into a structure and the address of that structure can be passed to arg.

a common mistake is to pass this parameter and then overwritten it when calling a new thread.Pitfall in pthread_create() • arg is a pointer to data. . • 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.

Gets the ID of the calling thread.Causes the current thread to yield its execution in favor of another thread with the same or greater priority.Get the Thread Identifier • pthread_self() . . void pthread_yield( void ). • Yield Thread Execution pthread_yield() . pthread_t pthread_self( void ).

be careful that there is no sharing of arguments.Warning If you create multiple threads. 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() pthreads. Some threads may not be able to read the arguments desired to them.hawaii.pdf . solution: use pthread_yield() after pthread_create() • Safe way: have a separate arguments for each thread http://navet.

int sig ).h> int kill( pid_t target. int sig ). .h> #include <signal. #include <sys/types. int tkill( pid_t tid.sends a signal to a thread.Send a Signal to a Thread • pthread_kill() .

target must be a process. 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() sends the signal sig to the thread specified by tid. The sig argument must be from the list given in signal. . tkill() is Linux specific.• kill() sends the signal sig to the thread specified by target. Do not use tkill() if you plan on making your program portable.

• The pthread_exit() function terminates the calling thread. . • Otherwise. the thread's ID and the exit status specified by status are retained until the thread is waited for. • If the calling thread is not detached. status is ignored and the thread's ID can be reclaimed immediately. • pthread_exit() . void pthread_exit( void *status ).Terminate a Thread • The thread returns from its start routine. All thread-specific data bindings are released.terminates a thread.

Wait for Thread Termination • pthread_join() . • When status is not NULL. void **status ). it points to a location that is set to the exit status of the terminated thread when pthread_join() returns successfully. int pthread_join( pthread_t wait_for. • 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.waits for a thread to terminate. .pthread_join() https://computing.

) • thr_getprio().Related Functions • thr_sigsetmask() – accesses the signal mask of the calling thread • pthread_key_create().get and set thread concurrency level (Concurrency: Many threads could be operating concurrently.get and set thread priority . on a multi threaded kernel. thr_setprio() . thr_setconcurrency() . thr_getspecific() maintain thread-specific data • thr_getconcurrency(). thr_setspecific().

Programming with Synchronization use Mutex For protecting critical areas of code .

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

. Use pthead_mutex_lock() to lock the mutex pointed by mp.Lock a mutex pthread_mutex_lock() int pthead_mutex_lock( pthread_mutex_t *mp ). the calling thread blocks until the mutex becomes available (blocked threads wait on a prioritized queue). When pthread_mutex_lock() returns. the mutex is locked and the calling thread is the owner. When the mutex is already locked.

} .pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER. { \\ CRITICAL SECTION } pthread_mutex_unlock( &mutex1 ). if( condition holds) { pthread_mutex_lock( &mutex1 ).

this call returns with an error. When the mutex is already locked.Lock with a Nonblocking Mutex int pthread_mutex_trylock( pthread_mutex_t *mp). . the mutex is locked and the calling thread is the owner. Otherwise. This function is a non-blocking version of pthread_mutex_lock(). • Use pthread_mutex_trylock() to attempt to lock the mutex pointed to by mp.

Unlock a Mutex int pthread_mutex_unlock( pthread_mutex_t *mp). • The mutex must be locked and the calling thread must be the one that last locked the mutex (the owner). . • Use the pthread_mutex_unlock() to unlock the mutex pointed to by mp.

destroys mutex state .Related Functions • pthead_mutex_init() – dynamically initializes a mutual exclusion lock • pthread_mutex_destroy() .

while( condition_is_false ) pthread_cond_wait(). .Condition Variables • Use condition variables to atomically block threads until a particular condition is true. pthread_mutex_lock(). pthread_mutex_unlock(). • Always use condition variables together with a mutex lock.

Block on a Condition Variable int pthread_cond_wait( pthread_cond_t *cvp. • 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. or when interrupted by delivery of a signal. . pthread_mutex_t *mp ). pthread_cond_broadcast(). • The blocked thread can be awakened by pthread_cond_signal().

the pthread_cond_signal() has no effect. • When no threads are blocked on the condition variable.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.

blocks until a specified event • pthread_cond_broadcast() .unblocks all threads • pthread_cond_destroy() .Related Functions • pthread_cond_init() .destroys condition variable state .initializes a condition variable • pthread_cond_timedwait() .

ASSIGNMENT 2 Mutual Exclusion .

who is away at college and therefore constantly drains financial resources. Jennifer Sanders(the mother). and glass. suction cups. 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. a home maker who doesn't contribute anything but only takes a very small amount at a time.PROBLEM STATEMENT Your assignment is to create a banking system. she also keeps track of the finances and makes sure there's enough money in the savings account. Jill Sanders(the daughter). He spends a lot and makes a lot. with threads that simulate the Sanders family accessing two accounts(checking and savings). .

txt.mst.txt • Each file describe the usage pattern of each • The text file inputs are available on: http://web.txt http://web. http://web. Pattern of entry in input file are: Character Account Amount ( example: d/w/t 0/1 50) .edu/~ercal/284/Asg-2/


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 .

mother and daughter • Join each thread using pthread_join() to wait for each thread‟s termination .MAIN FUNCTION • Create three threads using pthread_create() to simulate father.

Passing Multiple Arguments • Each Thread has its id and file: To pass the data like threadID. } http://web. = I.mst. a structure can be implemented holding threadID and corresponding inputfile. Main() { Eg THREADi. THREADi. FOR EXAMPLEstruct Eg { mem1 (inputfile) mem2 – number }. inputfile etc.inputfile = arg[i].txt .

(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. NULL. [USE RETURN VALUE OF pthread_create()] • Join each thread using pthread_join() in main.DIFFERENT THREADS FOR DIFFERENT USERS • pthread_create( &threadid. . startroutine.

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.START ROUTINE WHICH WILL SIMULATE THE OPERATIONS TO BE DONE BY EACH THREAD • Each THREADi is passed as parameter of start_routine(). account AND amount) } • usleep(random amount of time) //put thread to execute in interleaved way .

the account being operated needs to be locked by a mutex lock.MUTEX LOCKS ON EACH ACCOUNT • For withdraw and deposit functions. .Pay attention to Deadlock: if one lock has been obtained in a thread other than transfer. then a deadlock happens. both the accounts need to be locked by mutex locks. • For transfer function (between these two accounts only).

\\ CRITICAL SECTION INCREASE BALANCE IN ACCOUNT AND PRINT STATEMENT pthread_mutex_unlock( &mutex_saving ).EXAMPLE DEPOSIT FUNCTION: ONLY ONE LOCK FOR CHECKING OR SAVING if(account is CHECKING) { pthread_mutex_lock( &mutex_checking ). } else { pthread_mutex_lock( &mutex_saving ). } . \\ CRITICAL SECTION INCREASE BALANCE IN ACCOUNT AND PRINT STATEMENT pthread_mutex_unlock( &mutex_checking ).

} .TRANSFER FUNCTION: TWO LOCKS FOR CHECKING AND SAVING PAY 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 SECTION TRANSFER BALANCE BETWEEN CHECKING ACCOUNT AND SAVING ACCOUNT AND PRINT STATEMENT pthread_mutex_unlock( &mutex_saving ). pthread_mutex_unlock( &mutex_checking ).

• if(t from checking and checkingbalance <0 ) deny action. print warning • if(t from checking and wamount > checkingbalance and checkingbalance > 0) allow balance to go negative. print warning . • if(w or t from saving and savingsbalance is -) deny action. print warning.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.

"Bruce deposited x dollars. withdraws. New balance total: y") • Compile command: g++ assignment2..Useful Information • When the user deposits. or transfers.cpp –o assignment2 –lpthread • Run command: assignment2 filename1 filename2 filename3 . we should see a message to that effect. (e.g.

after running.SAMPLE RUN Command: “script mySession. New balance: 60 Jill:Withdrawal of 13 successful. ./assignment2 father daughter mother Jennifer:You do not have 37 dollars in checking to transfer. 28 dollars remain in your savings account. New balance: 28 Bruce:32 dollars deposited in checking. Bruce:14 dollars deposited in savings. Jennifer:You do not have 49 dollars in savings to transfer. Jill:Withdrawal of 5 successful. Bruce:14 dollars deposited in checking. Jennifer:14 dollars has been transferred from savings to checking. Jennifer:10 dollars has been transferred from checking to savings. 47 dollars remain in your checking account. New Balance: 14 Jill:Withdrawal of 30 failed.User 2:33 dollars has been transferred from checking to savings. “exit” [cchv5f@dell12 assignment2]$.txt”. You only have 14 dollars available in savings.

Questions? THANK YOU  .

Sign up to vote on this title
UsefulNot useful