1 / 42

THREAD IMPLEMENTATION

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

Download Presentation

THREAD IMPLEMENTATION

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. THREAD IMPLEMENTATION For parallel processing

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

  3. Create a Thread pthread_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.  

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

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

  6. #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.

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

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

  9. Warning If 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 thread http://navet.ics.hawaii.edu/~casanova/courses/ics432_fall08/slides/ics432_pthreads.pdf

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

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

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

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

  14. pthread_join() https://computing.llnl.gov/tutorials/pthreads/#Abstract

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

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

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

  18. 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 the mutex is already locked, 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.

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

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

  21. 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).

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

  23. 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();

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

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

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

  27. ASSIGNMENT 2 Mutual Exclusion

  28. PROBLEM STATEMENT Your 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.

  29. 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)

  30. COMPONENTS OF THE SOLUTION APPROACH • TWO DIFFERENT ACCOUNTS – CHECKING AND SAVING (global variables) • MAIN FUNCTION • DIFFERENT THREADS FOR DIFFERENT USERS • START ROUTINE WHICH WILL SIMULATE THE OPERATIONS TO BE DONE BY EACH THREAD • THREE DIFFERENT OPERATIONS ON EACH ACCOUNT (DEPOSIT, WITHDRAWAL, TRANSFER) • MUTEX LOCKS ON EACH ACCOUNT

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

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

  33. Passing Multiple Arguments • Each Thread has its id and file: To pass the data like threadID, inputfile etc, a structure can be implemented holding threadID 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

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

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

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

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

  38. 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 ); }

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

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

  41. 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: 14 Jill: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: 28 Bruce:32 dollars deposited in checking. New balance: 60 Jill: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.

  42. Questions?THANK YOU 

More Related