THREAD IMPLEMENTATION For parallel processing. Steps involved Creation Creates a thread with a thread id. Detach and Join All threads must be detached.

Slides:



Advertisements
Similar presentations
Programming with Posix Threads CS5204 Operating Systems.
Advertisements

Pthreads & Concurrency. Acknowledgements  The material in this tutorial is based in part on: POSIX Threads Programming, by Blaise Barney.
Multi-core Programming Programming with Posix Threads.
PTHREADS These notes are from LLNL Pthreads Tutorial
Computer Architecture II 1 Computer architecture II Programming: POSIX Threads OpenMP.
8-1 JMH Associates © 2004, All rights reserved Windows Application Development Chapter 10 - Supplement Introduction to Pthreads for Application Portability.
Lecture 18 Threaded Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
B.Ramamurthy1 POSIX Thread Programming 2/14/97 B.Ramamurthy.
Unix Threads operating systems. User Thread Packages pthread package mach c-threads Sun Solaris3 UI threads Kernel Threads Windows NT, XP operating systems.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
Pthread II. Outline Join Mutex Variables Condition Variables.
Threads Chapter 4. Modern Process & Thread –Process is an infrastructure in which execution takes place  (address space + resources) –Thread is a program.
Netprog Threads Programming1 Threads Programming Refs: Chapter 23.
Pthread (continue) General pthread program structure –Encapsulate parallel parts (can be almost the whole program) in functions. –Use function arguments.
Introduction to Pthreads. Pthreads Pthreads is a POSIX standard for describing a thread model, it specifies the API and the semantics of the calls. Model.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Atomic Operations David Monismith cs550 Operating Systems.
Thread Synchronization with Semaphores
10/16/ Realizing Concurrency using the thread model B. Ramamurthy.
Today’s topic Pthread Some materials and figures are obtained from the POSIX threads Programming tutorial at
B. RAMAMURTHY 10/24/ Realizing Concurrency using the thread model.
Operating Systems CMPSC 473 Multi-threading models Tutorial on pthreads Lecture 10: September Instructor: Bhuvan Urgaonkar.
Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
Includes slides from course CS194 at UC Berkeley, by prof. Katherine Yelick Shared Memory Programming Pthreads: an overview Ing. Andrea Marongiu
Programming with POSIX* Threads Intel Software College.
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
Professor: Shu-Ching Chen TA: Samira Pouyanfar.  An independent stream of instructions that can be scheduled to run  A path of execution int a, b; int.
Pthreads: A shared memory programming model
Threads CSCE Thread Motivation Processes are expensive to create. Context switch between processes is expensive Communication between processes.
Threads Chapter 26. Threads Light-weight processes Each process can have multiple threads of concurrent control. What’s wrong with processes? fork() is.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
POSIX Synchronization Introduction to Operating Systems: Discussion Module 5.
Pthreads.
Pthreads #include pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 2 ; pthread_create(&tid,
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Unix System Calls and Posix Threads.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
Chapter 6 P-Threads. Names The naming convention for a method/function/operation is: – pthread_thing_operation(..) – Where thing is the object used (such.
Unix Internals Concurrent Programming. Unix Processes Processes contain information about program resources and program execution state, including: Process.
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Threads A thread is an alternative model of program execution
PThread Synchronization. Thread Mechanisms Birrell identifies four mechanisms commonly used in threading systems –Thread creation –Mutual exclusion (mutex)
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
Working with Pthreads. Operations on Threads int pthread_create (pthread_t *thread, const pthread_attr_t *attr, void * (*routine)(void*), void* arg) Creates.
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
Case Study: Pthread Synchronization Dr. Yingwu Zhu.
A thread is a basic unit of CPU utilization within a process Each thread has its own – thread ID – program counter – register set – stack It shares the.
Lesson One – Creating a thread
Principles of Operating Systems Lecture 11
Shared-Memory Programming with Threads
Threads Threads.
Netprog: Threads Programming
Copyright ©: Nahrstedt, Angrave, Abdelzaher
PTHREADS These notes are from LLNL Pthreads Tutorial
Multithreading Tutorial
Principles of Operating Systems Lecture 8
Realizing Concurrency using Posix Threads (pthreads)
Lecture 14: Pthreads Mutex and Condition Variables
PTHREADS AND SEMAPHORES
Multithreading Tutorial
Threads Chapter 4.
Pthread Prof. Ikjun Yeom TA – Mugyo
Multithreading Tutorial
Multithreading Tutorial
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Lecture 14: Pthreads Mutex and Condition Variables
Realizing Concurrency using Posix Threads (pthreads)
POSIX Threads(pthreads)
Presentation transcript:

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

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.

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

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.

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

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

Send a Signal to a Thread pthread_kill() - sends a signal to a thread. #include int kill( pid_t target, int sig ); int tkill( pid_t tid, int sig );

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.

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.

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.

pthread_join()

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

Programming with Synchronization use Mutex For protecting critical areas of code

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.

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.

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

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.

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

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

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

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.

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.

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

ASSIGNMENT 2 Mutual Exclusion

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.

INPUT The text file inputs are available on: father.txthttp://web.mst.edu/~ercal/284/Asg-2/asg2- father.txt, mother.txt 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)

COMPONENTS OF THE SOLUTION APPROACH 1)TWO DIFFERENT ACCOUNTS – CHECKING AND SAVING (global variables) 2)MAIN FUNCTION 3)DIFFERENT THREADS FOR DIFFERENT USERS 4)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

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

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

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

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.

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

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.

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

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

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

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

SAMPLE RUN Command: “script mySession.txt”, after running, “exit” 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.

Questions? THANK YOU