S -1 Posix Threads. S -2 Thread Concepts Threads are "lightweight processes" –10 to 100 times faster than fork() Threads share: –process instructions,

Slides:



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

1 Threads. 2 Real Life Example?  Process  “system programming” course  Different from “internet engineering”  Thread  homework, Reading, Self-assessment.
Threads. What do we have so far The basic unit of CPU utilization is a process. To run a program (a sequence of code), create a process. Processes are.
Pthreads & Concurrency. Acknowledgements  The material in this tutorial is based in part on: POSIX Threads Programming, by Blaise Barney.
Threads Lab اللهم علمنا ما ينفعنا،،، وانفعنا بما علمتنا،،، وزدنا علماً
Threads By Dr. Yingwu Zhu. Review Multithreading Models Many-to-one One-to-one Many-to-many.
Computer Architecture II 1 Computer architecture II Programming: POSIX Threads OpenMP.
Precept 3 COS 461. Concurrency is Useful Multi Processor/Core Multiple Inputs Don’t wait on slow devices.
Fork Fork is used to create a child process. Most network servers under Unix are written this way Concurrent server: parent accepts the connection, forks.
Threads 1 CS502 Spring 2006 Threads CS-502 Spring 2006.
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.
Netprog Threads Programming1 Threads Programming Refs: Chapter 23.
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.
PRINCIPLES OF OPERATING SYSTEMS Lecture 6: Processes CPSC 457, Spring 2015 May 21, 2015 M. Reza Zakerinasab Department of Computer Science, University.
The University of Adelaide, School of Computer Science
Thread Synchronization with Semaphores
10/16/ Realizing Concurrency using the thread model B. Ramamurthy.
Programming with TCP – III 1. Zombie Processes 2. Cleaning Zombie Processes 3. Concurrent Servers Using Threads  pthread Library Functions 4. TCP Socket.
Today’s topic Pthread Some materials and figures are obtained from the POSIX threads Programming tutorial at
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.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
POSIX Threads Programming Operating Systems. Processes and Threads In shared memory multiprocessor architectures, such as SMPs, threads can be used to.
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.
ECE 297 Concurrent Servers Process, fork & threads ECE 297.
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
Source: Operating System Concepts by Silberschatz, Galvin and Gagne.
CS333 Intro to Operating Systems Jonathan Walpole.
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 and Locking Ioctl operations. Threads Lightweight processes What’s wrong with processes? –fork() is expensive – 10 to 100 times slower –Inter.
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.
UNIX Socket Programming CS 6378 Project Reference Book: Unix Network programming: Networking APIs: Sockets and XTI (2nd edition), Prentice Hall >> Threads.
Pthreads.
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.
Page 1 threads CS 360, WSU Vancouver POSIX Threads 1. Background 2. Threads vs. Processes 3. Thread Synchronization 4. Mutex Variables 5. Condition Variables.
Thread S04, Recitation, Section A Thread Memory Model Thread Interfaces (System Calls) Thread Safety (Pitfalls of Using Thread) Racing Semaphore.
NCHU System & Network Lab Lab #6 Thread Management Operating System Lab.
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
POSIX THREADS. What is a thread? Multiple stands of execution in a single program are called threads. In other words, a thread is a sequence of control.
1 Introduction to Threads Race Conditions. 2 Process Address Space Revisited Code Data OS Stack (a)Process with Single Thread (b) Process with Two Threads.
Tutorial 4. In this tutorial session we’ll see Threads.
Threads Some of these slides were originally made by Dr. Roger deBry. They include text, figures, and information from this class’s textbook, Operating.
Chapter 5: Process Synchronization – Part 3
Threads Threads.
Netprog: Threads Programming
Boost String API & Threads
Copyright ©: Nahrstedt, Angrave, Abdelzaher
CS399 New Beginnings Jonathan Walpole.
Linux Processes & Threads
Multithreading Tutorial
Operating Systems Lecture 13.
Multithreading Tutorial
Unix System Calls and Posix Threads
Pthread Prof. Ikjun Yeom TA – Mugyo
Operating System Concepts
Multithreading Tutorial
Multithreading Tutorial
Realizing Concurrency using Posix Threads (pthreads)
Tutorial 4.
POSIX Threads(pthreads)
Presentation transcript:

S -1 Posix Threads

S -2 Thread Concepts Threads are "lightweight processes" –10 to 100 times faster than fork() Threads share: –process instructions, most data, file descriptors, signal handlers/dispositions, current working directory, user/group Ids Each thread has its own: –thread ID, set of registers (incl. Program counter and stack pointer), stack (local vars, return addresses), errno, signal mask, priority Posix threads will (we think) be the new UNIX thread standard see CDF man pages for pthread, or read Chapter 23 in Unix Network Programming by Richard Stevens, 1998, Prentice Hall

S -3 Creating a PThread #include int pthread_create(pthread_t *tid, pthread_attr_t *attr, void *(*func)(void *), void *arg) tid is unique within a process, returned by function attr –sets priority, scheduling method, initial stack size, daemon status –can specify as NULL func –function to call to start thread –accepts one void * argument, returns one void * arg is the argument to pass to func

S -4 Creating a Pthread [cont'd] pthread_create() returns 0 if successful, a +ve error code if not does not set errno, but returns compatible codes can use strerror() to print error messages Thread Termination #include int pthread_join(pthread_t tid, void **status) tid – the thread ID of the thread to wait for –cannot wait for any thread (cf. wait() )

S -5 Thread Termination [cont'd] status, if not NULL, returns the void * returned by the thread when it terminates a thread can terminate by –returning from func() –the main() function exiting (all threads terminate) –pthread_exit() #include void pthread_exit(void *status); a second way to exit, returns status explicitly status must not point to an object local to thread, as these disappear when the thread terminates

S -6 "Detaching" Threads #include int pthread_detach(pthread_t tid); threads are either joinable or detachable if a thread is detached, its termination cannot be tracked with pthread_join() … it becomes a daemon thread #include pthread_t pthread_self(void); returns the thread ID of the thread which calls it often will see pthread_detach(pthread_self())

S -7 Passing Arguments to Threads pthread_t thread_ID; int fd, result ; result = pthread_create(&thread_ID, (pthread_attr_t *)NULL, myThreadFcn, (void *)&fd); if (result != 0) printf("Error: %s\n", strerror(result)); we can pass any variable (including a structure or array) to our thread function; assumes thread function knows what type to expect

S -8 Thread-Safe Functions Not all functions can be called from threads (e.g. strtok() ) –many use global/static variables –new versions of UNIX have thread-safe replacements, like strtok_r() Safe: –ctime_r(), gmtime_r(), localtime_r(), rand_r(), strtok_r() Not Safe: –ctime(), gmtime(), localtime(), rand(), strtok(), gethostXXX(), inet_toa() could use semaphores to protect access

S -9 PThread Semaphores #include int pthread_mutex_init(pthread_mutex_t *name, const pthread_mutexattr_t *attr); int pthread_mutex_destroy(pthread_mutex_t *name); int pthread_mutex_lock(pthread_mutex_t *name); int pthread_mutex_trylock(pthread_mutex_t *name); int pthread_mutex_unlock(pthread_mutex_t *name); pthread semaphores are easier to use than semget() and semop() all mutexes must be global only the thread that locks a mutex can unlock it

S -10 PThread Semaphores [cont'd] pthread_mutex_t myMutex ; int status ; status = pthread_mutex_init(&myMutex, NULL) ; if (status != 0) printf("Error: %s\n", strerror(status)); pthread_mutex_lock(&myMutex); /* critical section here */ pthread_mutex_unlock(&myMutex); status = pthread_mutex_destroy(&myMutex); if (status != 0) printf("Error: %s\n", strerror(status));

S -11 Concurrency Concepts

S -12 Non-determinism A process is deterministic when it always produces the same result when presented with the same data; otherwise a process is called non-deterministic j = 10 print j j = 100 exit Evaluation proceeds non-deterministically in one of two ways, producing an output of 10 or 100 Race conditions lead to non-determinism, and are generally undesirable

S -13 Deadlocks A concurrent program is in deadlock if all processes are waiting for some event that will never occur Typical deadlock pattern: Process 1 is holding resource X, waiting for Y Process 2 is holding resource Y, waiting for X Process 1 will not get Y until Process 2 releases it Process 2 will not release Y until it gets X, which Process 1 is holding, waiting for …

S -14 Dining Philosophers N philosophers are seated in a circle, one chopstick between each adjacent pair Each philosopher needs two chopsticks to eat, a left chopstick and a right chopstick A typical philosopher process alternates between eating and thinking (see next slide)

S -15 Philosopher Process loop endloop

S -16 Deadlock Example For N =2, call philosophers P1 and P2, and chopsticks C1 and C2 Deadlocking sequence: P1 requests; gets C1 P2 requests; gets C2 P1 requests; WAITS for C2 P2 requests; WAITS for C1 ** DEADLOCK ** Can avoid deadlock if the philosopher processes request both chopsticks at once, and then the get both or wait until both are available

S -17 Comments on Deadlock In practice, deadlocks can arise when waiting for some reusable resources. For example, an operating system may be handling several executing jobs, none of which has enough room to finish (and free up memory for the others) Operating systems may detect/avoid deadlocks by: –checking continuously on requests for resources –refusing to allocate resources if allocation would lead to a deadlock –terminating a process that is responsible for deadlock One can have a process that sits and watches, and can break a deadlock if necessary. This process may be invoked: –on a timed interrupt basis –when a process wants to queue for a resource –when deadlock is suspected (i.e.: CPU utilization has dropped to 0)

S -18 Indefinite Postponement Indefinite postponement occurs when a process is blocked waiting for an even that can, but will not occur in some future execution sequence This may arise because other processes are “ganging up” on a process to “starve” it During indefinite postponement, the overall system does not grind to a halt, but treats some of its processes unfairly Indefinite postponement can be avoided by having priority queues which serve concurrent processes on a first-come, first-served basis UNIX semaphores do this, using a FIFO (first-in, first-out) queue for all requests