Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design.

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
Lecture 4: Concurrency and Threads CS 170 T Yang, 2015 Chapter 4 of AD textbook.
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.
POSIX Threads Nezer J. Zaidenberg. References  Advanced programming for the UNIX environment (2nd edition. This material does not exist in first edition)
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.
Threads? Threads allow us to have multiple tasks active at the same time in one executable –think of a server handling multiple connections Each thread.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
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.
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.
04/10/25Parallel and Distributed Programming1 Shared-memory Parallel Programming Taura Lab M1 Yuuki Horita.
Operating Systems CMPSC 473 Multi-threading models Tutorial on pthreads Lecture 10: September Instructor: Bhuvan Urgaonkar.
POSIX Threads Nezer J. Zaidenberg. References  Advanced programming for the UNIX environment (2nd edition chapter This material does not exist.
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,
What is a thread? process: an address space with 1 or more threads executing within that address space, and the required system resources for those threads.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Semaphore and Mutex Operations.
Programming with POSIX* Threads Intel Software College.
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.
S -1 Posix Threads. S -2 Thread Concepts Threads are "lightweight processes" –10 to 100 times faster than fork() Threads share: –process instructions,
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
POSIX Synchronization Introduction to Operating Systems: Discussion Module 5.
Pthreads.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Software Systems Advanced Synchronization Emery Berger and Mark Corner University.
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
Page 1 threads CS 360, WSU Vancouver POSIX Threads 1. Background 2. Threads vs. Processes 3. Thread Synchronization 4. Mutex Variables 5. Condition Variables.
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.
Programming with Threads. Threads  Sometimes called a lightweight process  smaller execution unit than a process  Consists of:  program counter 
pThread synchronization
回到第一頁 What are threads n Threads are often called "lightweight processes” n In the UNIX environment a thread: u Exists within a process and uses the process.
Case Study: Pthread Synchronization Dr. Yingwu Zhu.
Synchronization and Semaphores
Lecture 5 : Pthread Programming
PThreads.
Threads in C Caryl Rahn.
Shared-Memory Programming with Threads
Threads Threads.
Netprog: Threads Programming
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Chapter 4: Threads.
PTHREADS These notes are from LLNL Pthreads Tutorial
Multithreading Tutorial
POSIX Threads 1. Background 2. Threads vs. Processes
PTHREADS AND SEMAPHORES
Multithreading Tutorial
Thread Programming.
Pthread Prof. Ikjun Yeom TA – Mugyo
Operating System Concepts
Multithreading Tutorial
Synchronization Primitives – Semaphore and Mutex
Multithreading Tutorial
Tutorial 4.
Shared Memory Programming with Pthreads
POSIX Threads(pthreads)
Presentation transcript:

Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design

Processes vs Threads Stack Data Text Process1 Stack Data Text Process2 Stack2 Data Text Thread1 Stack1 Thread2

Some Terms Thread Safe Reentrant Multi-threaded POSIX

What does POSIX mean? Portable Operating System Interface for Unix" is the name of a family of related standards specified by the IEEE to define the application programming interface (API), along with shell and utilities interfaces, for software compatible with variants of the UNIX operating system, although the standard can apply to any operating system.

Commonly used pthread API’s pthread_create() pthread_detach() pthread_equal() pthread_exit() pthread_join() pthread_self() sched_yield() pthread_cancel() pthread_mutex_init() pthread_mutex_destroy() pthread_mutex_lock() pthread_mutex_trylock() pthread_mutex_unlock()

pthread API’s cont’d pthread_cond_destroy( ) pthread_cond_init( ) pthread_cond_broadcast( ) pthread_cond_signal( ) pthread_cond_timedwait() pthread_cond_wait() pthread_mutexattr_gettype() pthread_mutexattr_settype() pthread_setconcurrency() pthread_getconcurrency() pthread_mutexattr_getprotocol() pthread_mutexattr_setprotocol() pthread_setschedparam() pthread_attr_setschedpolicy() sched_get_priority_max() sched_set_priority_min()

#include #include void *thread_routine(void* arg) { printf("Inside newly created thread \n"); } void main() { pthread_t thread1; pthread_create(&thread1, NULL, thread_routine, NULL); pthread_create( &thread_id, NULL, thread_routine, NULL ); printf("Inside main thread \n"); pthread_join( thread_id, NULL ); } pluto.nvc.cs.vt.edu$ cc p.c -lpthread

int pthread_create( pthread_t *tid, //Thread ID returned by the system const pthread_attr_t *attr, //optional attributes void *(*start)(void *), //thread function void *arg // Arguments to start function ); Description: Create a thread running the start function.

int pthread_join( pthread_t thread, // ID of thread void **value_ptr // return value of thread ); Description: Wait for thread to terminate, and return thread’s exit value if value_ptr is not NULL. This also detaches thread on successful completion.

int pthread_exit( void *value_ptr, // Return value ); Description: Terminate the calling thread, returning the value value_ptr to any joining thread. int pthread_equal( pthread_t t1, // ID of thread1 pthread_t t2, // ID of thread2 ); Description: Return zero if equal. Non-zero if not.

int pthread_cancel( pthread_t threadID // ID of thread to cancel ); Description: Cancellation provides a way to request that a thread terminate gracefully when you no longer need it to complete its normal execution. Each thread can control how and whether cancellation affect it and repair the shared state as it terminates due to cancellation. pthread_t pthread_self(); Description: Used to get the ID of the current thread. int sched_yield(); Description: Make the calling thread from running state to ready state, giving way for other threads.

Thread Cancellation Example: void *thread_routine(void* arg){ printf("Inside thread \n"); sleep( 30 ); printf("After sleep \n"); } void main(){ pthread_t thread_id; void *thread_result =0; pthread_create( & thread_id, NULL, thread_routine, NULL ); sleep(3); printf("Main thread\n"); pthread_cancel( thread_id ); printf("End of main\n"); }

If multiple threads want to wait for the completion of a thread, they cannot do so by calling pthread_join() Instead, these threads should wait on a condition variable which is set by the waited thread after completion. Main thread vs Other Threads 1) Input arguments are different. 2) When main thread returns all other threads are aborted. 3) If you want the main thread to exit, but other threads to keep running then call pthread_exit in the main function. Avoid fork and signals in threads.

Synchronization pthread_mutex_init() pthread_mutex_destroy() pthread_mutex_lock() pthread_mutex_trylock() pthread_mutex_unlock()

Reasons for Synchronization Need For getting shared access to resources (variables, buffers, devices, etc.) – Critical variables; critical sections. – For communicating. Cases where cooperating processes need not synchronize to share resources: – All processes are read only. – All processes are write only. – One process writes (atomically), all other processes read.

Atomicity What does atomic mean? Characteristics of ‘trouble situations’: – Multiple processes doing updates non-atomically. – Non-atomic write processes coupled with read or update processes

void *consumer(void* arg) { for(int I =0; I < 30 ; I ++ )mutex );,shared_data--; /* Critical Section. */ printf("data val=%d\n”, shared_data); } void main() { pthread_t thread_id; pthread_create(&thread_id, NULL, consumer, NULL); for(int I =0; I < 30 ; I ++ ) shared_data ++; /* Critical Section. */ printf("End of main =%d\n”, shared_data); }

Formal Definition of Critical Sections The overlapping portion of each process, where the shared variables are being accessed. Necessary and sufficient conditions for a solution to the critical section problem: – Mutual Exclusion – Progress – Bounded Waiting

Mutual Exclusion Simplest and most efficient thread synchronization mechanism A special variable that can be either in – locked state: a distinguished thread that holds or owns the mutex; or – unlocked state: no thread holds the mutex When several threads compete for a mutex, one wins. The rest block at that call – The mutex also has a queue of threads that are waiting to hold the mutex. POSIX does not require that this queue be accessed FIFO

POSIX Mutex-related Functions int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr); Also see PTHREAD_MUTEX_INITIALIZER int pthread_mutex_destroy(pthread_mutex_t *mutex); int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_trylock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex);

Example #include static pthread_mutex_t my_lock = PTHREAD_MUTEX_INITIALIZER; void *mythread(void *ptr) { long int i,j; while (1) { pthread_mutex_lock (&my_lock); for (i=0; i<10; i++) { printf ("Thread %d\n", (int) ptr); for (j=0; j< ; j++); } pthread_mutex_unlock (&my_lock); for (j=0; j< ; j++); } int main (int argc, char *argv[]) { pthread_t thread[2]; pthread_create(&thread[0], NULL, mythread, (void *)0); pthread_create(&thread[1], NULL, mythread, (void *)1); getchar(); }