8-1 JMH Associates © 2004, All rights reserved Windows Application Development Chapter 10 - Supplement Introduction to Pthreads for Application Portability.

Slides:



Advertisements
Similar presentations
CS Lecture 4 Programming with Posix Threads and Java Threads George Mason University Fall 2009.
Advertisements

Threads Programming Thread creation Synchronization.
Programming with Posix Threads CS5204 Operating Systems.
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
Chap. 23 Threads (1) Threads v.s. Fork (2) Basic Thread Functions #include int pthread_create ( pthread_t *tid, const pthread_attr_t *attr, void *(*func)(void.
Computer Architecture II 1 Computer architecture II Programming: POSIX Threads OpenMP.
Lecture 18 Threaded Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
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.
Comp 422: Parallel Programming Shared Memory Multithreading: Pthreads Synchronization.
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.
THREAD IMPLEMENTATION For parallel processing. Steps involved Creation Creates a thread with a thread id. Detach and Join All threads must be detached.
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.
Thread-Safe Programming Living With Linux. Thread-Safe Programming Tommy Reynolds Fedora Documentation Project Steering Committee
June-Hyun, Moon Computer Communications LAB., Kwangwoon University Chapter 26 - Threads.
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.
Copyright ©: University of Illinois CS 241 Staff1 Synchronization and Semaphores.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
Programming with POSIX* Threads Intel Software College.
Condition Variables u A condition variable is used to wait until a particular condition is true  like in a monitor u Always use condition variables together.
CSC Advanced Unix Programming, Fall, 2008 Monday, November 24 POSIX threads (pthreads)
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
Thread API Xiaohua Lu Office : CS 3310 Tel. : Office hours: 11-12,3-5 T,TR.
POSIX Synchronization Introduction to Operating Systems: Discussion Module 5.
POSIX Threads HUJI Spring 2011.
IT 325 Operating systems Chapter6.  Threads can greatly simplify writing elegant and efficient programs.  However, there are problems when multiple.
Pthreads.
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 11: Thread-safe Data Structures, Semaphores.
Pthreads #include pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 2 ; pthread_create(&tid,
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Software Systems Advanced Synchronization Emery Berger and Mark Corner University.
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.
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.
pThread synchronization
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
Case Study: Pthread Synchronization Dr. Yingwu Zhu.
Realizing Concurrency using the thread model
Realizing Concurrency using the thread model
PThreads.
Principles of Operating Systems Lecture 11
Shared-Memory Programming with Threads
Threads Threads.
Netprog: Threads Programming
Chapter 4: Threads.
PTHREADS These notes are from LLNL Pthreads Tutorial
Multithreading Tutorial
Realizing Concurrency using Posix Threads (pthreads)
Operating Systems Lecture 13.
Lecture 14: Pthreads Mutex and Condition Variables
Realizing Concurrency using the thread model
PTHREADS AND SEMAPHORES
Multithreading Tutorial
Threads Chapter 4.
Pthread Prof. Ikjun Yeom TA – Mugyo
Multithreading Tutorial
Multithreading Tutorial
Realizing Concurrency using the thread model
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:

8-1 JMH Associates © 2004, All rights reserved Windows Application Development Chapter 10 - Supplement Introduction to Pthreads for Application Portability

8-2 JMH Associates © 2004, All rights reserved OBJECTIVESOBJECTIVES Upon completion of this chapter, you will be able to:  Describe the Pthreads API  Compare Windows and Pthreads  Use the open source Pthreads library  Build portable threaded applications  Understand threading outside the Windows context

8-3 JMH Associates © 2004, All rights reserved 1. Pthreads Overview POSIX Pthreads features supported by:  An industry standard  Similar to Windows, with differences (Ex: Events)  Nearly every UNIX distribution – HP UX, Solaris, AIX, …  Linux  OpenVMS  Others  PLUS, an open source Windows distribution  Cautiously recommended – Trust but verify pthread.h pthreadVSE.lib pthreadVSE.dll

8-4 JMH Associates © 2004, All rights reserved 2. Thread Management and Creation A parent thread creates a child thread using: int pthread_create (pthread_t *thread, const pthread_attr_t *attr void *(*start) (void *), void *arg); Thread creation notes:  pthread_attr_t is NULL (for our purposes)  Use other values only when explicitly required  Parent and child concepts are for convenience only  Operating system does not maintain any such relationship  The main() program initial thread is special  Behaves differently from other threads

8-5 JMH Associates © 2004, All rights reserved Thread Startup The child thread is created in the ready state  It can run immediately Thread startup notes:  Parent and child threads can run in any order  Child thread might complete before (or after) any other  Complete all initialization before calling pthread_create()  Each child thread should have its own data structure  For parameters  For working storage  The parent thread initializes the structure and passes its address in arg

8-6 JMH Associates © 2004, All rights reserved Thread Running and Blocking The operating system scheduler runs a thread according to thread priorities and scheduling policies  A thread can run at any time  A thread may run until one of the following:  The thread times out and the operating system preempts it  The thread blocks due to a page fault  The thread terminates or is terminated  The thread yields the processor and moves to the ready state int sched_yield (void);  The thread blocks by calling a blocking function int pthread_join (pthread_t thread, void **value_ptr);

8-7 JMH Associates © 2004, All rights reserved Thread Termination The normal way for a thread to terminate is to return from its start function or to call int pthread_exit (void *value_ptr); The return value is the thread’s exit code  Exit code can be accessed by pthread_join() Resources created by a thread must be explicitly released

8-8 JMH Associates © 2004, All rights reserved 3. Mutexes A mutex, of object type pthread_mutex_t, can be initialized by assignment or a function call pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int pthread_mutex_init (pthread_mutex_t *mutex, pthread_mutexattr_t *attr); int pthread_mutex_destroy (pthread_mutex_t *mutex);

8-9 JMH Associates © 2004, All rights reserved Mutex Management Notes pthread_mutex_t  Do not copy a variable of type pthread_mutex_t  If declared outside the main function, it should have either extern or static storage class Each mutex must be initialized before it is used Static initialization with PTHREAD_MUTEX_INITIALIZER Dynamic initialization with pthread_mutex_init() When no longer required, destroy it to free kernel and user resources

8-10 JMH Associates © 2004, All rights reserved Locking and Unlocking a Mutex A thread can lock or own a mutex  A thread attempts to gain ownership with a try call int pthread_mutex_trylock ( pthread_mutex_t *mutex);  Returns with 0 if successful  Returns with EBUSY if the mutex is owned by another thread  A thread waits to gain ownership with lock call int pthread_mutex_lock (pthread_mutex_t *mutex);  Blocking call; will only return with mutex ownership  Returns with EINVAL if the parameter is not valid  Unlock a mutex int pthread_mutex_unlock ( pthread_mutex_t *mutex);

8-11 JMH Associates © 2004, All rights reserved Locking and Unlocking Notes  There is no timeout associated with pthread_mutex_lock()  If a thread terminates before it unlocks a mutex, the mutex remains locked  A mutex can have the recursive attribute  If pthread_mutex_trylock() fails, do not access the protected resources and do not unlock the mutex  Do not let a thread unlock a mutex it does not own  Exactly one blocked thread will be given mutex ownership  You cannot predict which one

8-12 JMH Associates © 2004, All rights reserved 4. Condition Variables A condition variable is used to signal that some event or state change has occurred  A mutex protects the whole state data structure  Multiple condition variables related to one mutex  Condition variables represent distinct states  New data available in a buffer  Buffer empty, buffer full, etc.  Signaled to awaken just one thread  Broadcast to awaken all waiting threads Combines: Signal, wait, wait sequence of the CVM

8-13 JMH Associates © 2004, All rights reserved Condition Variable Management pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int pthread_cond_init ( pthread_cond_t *cond, pthread_condattr_t *condattr); int pthread_cond_destroy ( pthread_cond_t *cond);

8-14 JMH Associates © 2004, All rights reserved Waiting on a Condition Variable Wait with either a blocking wait or a wait with a timeout  Both must specify a mutex  The calling thread must own the mutex before waiting on the condition variable int pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex); int pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *expiration); Returns ETIMEOUT if the timeout period expires

8-15 JMH Associates © 2004, All rights reserved Condition Variable Waiting Notes  A thread “waits” on a condition variable  All threads waiting on a condition variable at any one time must specify the same mutex  Distinct predicates should have distinct condition variables  Associate the condition variable with a state predicate  The mutex should be the one that protects the state variables that determine the predicate  Two distinct predicates  Invariant predicate  Condition variable predicate (implies invariant)  Condition variables are for signaling, not mutual exclusion

8-16 JMH Associates © 2004, All rights reserved Condition Variable Signal and Broadcast  Wake up a single waiting thread with int pthread_cond_signal ( pthread_cond_t *cond);  Cannot directly control which of several threads will awaken  Wake up all threads with int pthread_cond_broadcast ( pthread_cond_t *cond);  All waiting threads wake up and immediately block on the mutex  Only one thread, at most, gains mutex ownership immediately

8-17 JMH Associates © 2004, All rights reserved CV Waiting and Signaling Threads Thread AThread B Running Ready Running Ready Waiting on cond Lock (&state.guard) Unlock (&state.guard) Lock (&state.guard) Signal (&state.cond) change state variables Wait (&state.cond, &state.guard) Thread A does not own state.guard Running Blocked on guard Ready Thread A owns state.guard change state variables Unlock (&state.guard) ivp() : invariant predicate cvp() : condition variable predicate Run Preempt ivp( ) is true cvp( ) is true

8-18 JMH Associates © 2004, All rights reserved Safe Condition Variable Usage Test your predicate immediately before and immediately after the condition variable wait call  A simple while() loop achieves these tests  Develop two thread-safe functions: cvp() implies ivp()  They check the CV predicate and invariant predicate  They check relationships in the state variable structure  Must be called with the appropriate mutex locked  No need for a function for simple predicates

8-19 JMH Associates © 2004, All rights reserved Safe Condition Variable Usage typedef struct _state_t { pthread_mutex_t guard; pthread_cond_t cond;... other condition variables struct state_var_t state_var; } state_t state = { PTHREAD_MUTEX_INTIALIZER, PTHREAD_COND_INITIALIZER };... pthread_mutex_lock (&state.guard); /* Change the variables in the state structure */... state.state_var.xyz =... ; /* We know that ivp(&state) holds, wait for cvp(&state) */ /* Do not wait if cvp() already is true, avoid lost wakeup */ while (!cvp(&state)) pthread_cond_wait (&state.cond, &state.guard);... pthread_mutex_unlock (&state.guard);

8-20 JMH Associates © 2004, All rights reserved 5. Lab Exercise 10-pthreads Modify eventPC.c (Session 2) to use Pthreads eventPCPT.c is a solution