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.

Slides:



Advertisements
Similar presentations
Threads. Readings r Silberschatz et al : Chapter 4.
Advertisements

Pthreads & Concurrency. Acknowledgements  The material in this tutorial is based in part on: POSIX Threads Programming, by Blaise Barney.
Professor: Shu-Ching Chen TA: Hsin-Yu Ha.  An independent stream of instructions that can be scheduled to run  A path of execution int a, b; int c;
Day 10 Threads. Threads and Processes  Process is seen as two entities Unit of resource allocation (process or task) Unit of dispatch or scheduling (thread.
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.
Pthreads Operating Systems Hebrew University of Jerusalem Spring 2004.
Lecture 18 Threaded Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
Process Concept An operating system executes a variety of programs
Chapter 51 Threads Chapter 5. 2 Process Characteristics  Concept of Process has two facets.  A Process is: A Unit of resource ownership:  a virtual.
Chapter 4: Threads. From Processes to Threads 4.3 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7 th edition, Jan 23, 2005 Threads.
Chapter 4: Threads. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Threads A thread (or lightweight process) is a basic unit of CPU.
Process Management. Processes Process Concept Process Scheduling Operations on Processes Interprocess Communication Examples of IPC Systems Communication.
CGS 3763 Operating Systems Concepts Spring 2013 Dan C. Marinescu Office: HEC 304 Office hours: M-Wd 11: :30 AM.
Today’s Topics Introducing process: the basic mechanism for concurrent programming –Process management related system calls Process creation Process termination.
The University of Adelaide, School of Computer Science
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.
June-Hyun, Moon Computer Communications LAB., Kwangwoon University Chapter 26 - Threads.
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
POSIX Threads Programming Operating Systems. Processes and Threads In shared memory multiprocessor architectures, such as SMPs, threads can be used to.
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
Copyright ©: University of Illinois CS 241 Staff1 Threads Systems Concepts.
CS333 Intro to Operating Systems Jonathan Walpole.
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,
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.
Processes CS 6560: Operating Systems Design. 2 Von Neuman Model Both text (program) and data reside in memory Execution cycle Fetch instruction Decode.
1 Computer Systems II Introduction to Processes. 2 First Two Major Computer System Evolution Steps Led to the idea of multiprogramming (multiple concurrent.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
Threads A thread is an alternative model of program execution
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.
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.
1 Module 3: Processes Reading: Chapter Next Module: –Inter-process Communication –Process Scheduling –Reading: Chapter 4.5, 6.1 – 6.3.
B. RAMAMURTHY 5/10/2013 Amrita-UB-MSES Realizing Concurrency using the thread model.
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
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.
Realizing Concurrency using the thread model
Realizing Concurrency using the thread model
Threads in C Caryl Rahn.
Threads Threads.
CS399 New Beginnings Jonathan Walpole.
Multithreading Tutorial
Multithreading Tutorial
Realizing Concurrency using Posix Threads (pthreads)
Operating Systems Lecture 13.
Realizing Concurrency using the thread model
Multithreading Tutorial
Realizing Concurrency using the thread model
Operating System Concepts
Multithreading Tutorial
Multithreading Tutorial
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
CS510 Operating System Foundations
Andy Wang Operating Systems COP 4610 / CGF 5765
Andy Wang Operating Systems COP 4610 / CGF 5765
Sarah Diesburg Operating Systems COP 4610
Presentation transcript:

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 well protected from one another. Switching between processes is fairly expensive. Communications between processes are done through inter-process communication mechanisms. Running process requires the memory management system. Process I/O is done by the I/O subsystem.

Process for all concurrency needs? Consider developing a PC game: Different code sequences for different characters (soldiers, cities, airplanes, cannons, user controlled heroes) Each of the characters is more or less independent. We can create a process for each character. Any drawbacks? The action of a character usually depends on the game state (locations of other characters).  Implication on the process based implementation of characters? A lot of context switching.

What do we really need for a PC game? A way to run different sequences of code (threads of control) for different characters. Processes do this. A way for different threads of control to share data effectively. Processes are NOT designed to do this. Protection is not very important, a game is one application anyway. Process is an over-kill. Switching between threads of control must be as efficient as possible. Context switching is known to be expensive!!! Theads are created to do all of above.

Thread Process context Process ID, process group ID, user ID, and group ID Environment Working directory. Program instructions Registers (including PC) Stack Heap File descriptors Signal actions Shared libraries Inter-process communication tools What is absolutely needed to run a sequence of code (a thread of control)?

Process/Thread context What are absolutely needed to support a stream of instructions, given the process context? Process ID, process group ID, user ID, and group ID Environment Working directory. Program instructions Registers (including PC) Stack Heap File descriptors Signal actions Shared libraries Inter-process communication tools

Process and Thread

Threads Threads are executed within a process. Share process context means  easy inter-thread communication.  No protection among threads  but threads are intended to be cooperative. Thread context: PC, registers, a stack, misc. info. Much smaller than the process context!! Faster context switching Faster thread creation

Threads Threads are also called light-weight processes. traditional processes are considered heavy-weight. A process can be single-threaded or multithreaded. Threads become so ubiquitous that almost all modern computing systems use thread as the basic unit of CPU utilization.

More about threads OS view: A thread is an independent stream of instructions that can be scheduled to run by the OS. Software developer view: a thread can be considered as a “procedure” that runs independently from the main program. Sequential program: a single stream of instructions in a program. Multi-threaded program: a program with multiple streams Multiple threads are needed to use multiple cores/CPUs

Threads… Exist within processes Die if the process dies Use process resources Duplicate only the essential resources for OS to schedule them independently Each thread maintains Stack Registers Scheduling properties (e.g. priority) Set of pending and blocked signals (to allow different react differently to signals) Thread specific data

The Pthreads (POSIX threads) API Three types of routines: Thread management: create, terminate, join, and detach Mutexes: mutual exclusion, creating, destroying, locking, and unlocking mutexes Condition variables: event driven synchronizaiton. Mutexes and condition variables are concerned about synchronization. Why not anything related to inter-thread communication? The concept of opaque objects pervades the design of the API.

The Pthreads API naming convention Routine PrefixFunction Pthread_General pthread Pthread_attr_Thread attributes Pthread_mutex_mutex Pthread_mutexattrMutex attributes Pthread_cond_Condition variables Pthread_condaddrConditional variable attributes Pthread_key_Thread specific data keys

Compiling pthread programs Pthread header file Compiling pthread programs: gcc –lpthread aaa.c

Thread management routines Creation: pthread_create Termination: Return Pthread_exit Can we still use exit? Wait (parent/child synchronization): pthread_join

Creation Thread equivalent of fork() int pthread_create( pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg ); Returns 0 if OK, and non-zero (> 0) if error. Parameters for the routines are passed through void * arg. What if we want to pass a structure?

Termination Thread Termination Return from initial function. void pthread_exit(void * status) Process Termination exit() called by any thread main() returns

Waiting for child thread int pthread_join( pthread_t tid, void **status) Equivalent of waitpid() for processes

Detaching a thread The detached thread can act as daemon thread The parent thread doesn’t need to wait int pthread_detach(pthread_t tid) Detaching self : pthread_detach(pthread_self())

Some multi-thread program examples A multi-thread program example: example1.c Making multiple producers: example2.c What is going on in this program? How to fix it?

Matrix multiply and threaded matrix multiply Matrix multiply: C = A × B

Matrix multiply and threaded matrix multiply Sequential code: For (i=0; i<N; i++) for (j=0; j<N; j++) for (k=0; k<N; k++) C[I, j] = C[I, j] + A[I, k] * A[k, j] Threaded code program The calculation of c[I,j] does not depend on other C term. Mm_pthread.c.

PI calculation Sequential code: pi.c Threaded version: homework

Type of Threads Independent threads Cooperative threads

Independent Threads No states shared with other threads Deterministic computation Output depends on input Reproducible Output does not depend on the order and timing of other threads Scheduling order does not matter.

Cooperating Threads Shared states Nondeterministic Nonreproducible Example: 2 threads sharing the same display Thread AThread B cout << “ABC”;cout << “123”; You may get “A12BC3”

So, Why Allow Cooperating Threads? Shared resources e.g., a single processor Speedup Occurs when threads use different resources at different times mm_pthread.c Modularity An application can be decomposed into threads

Some Concurrent Programs If threads work on separate data, scheduling does not matter Thread AThread B x = 1;y = 2;

Some Concurrent Programs If threads share data, the final values are not as obvious Thread AThread B x = 1;y = 2; x = y + 1;y = y * 2; What are the indivisible operations?

Atomic Operations An atomic operation always runs to completion; it’s all or nothing e.g., memory loads and stores on most machines Many operations are not atomic Double precision floating point store on 32-bit machines

Suppose… Each C statement is atomic Let’s revisit the example…

All Possible Execution Orders Thread AThread B x = 1;y = 2; x = y + 1;y = y * 2; x = 1y = 2x = y + 1y = 2 y = y * 2 x = y + 1y = y * 2 x = y + 1 x = 1y = y * 2 x = 1 x = y + 1 A decision tree

All Possible Execution Orders Thread AThread B x = 1;y = 2; x = y + 1;y = y * 2; x = 1y = 2 x = y + 1y = 2 x = y + 1y = y * 2y = 2 y = y * 2 x = y + 1 x = 1y = y * 2 x = 1 x = y + 1 (x = ?, y = ?) (x = 1, y = ?) (x = ?, y = ?) (x = ?, y = 2) (x = ?, y = 4) (x = 1, y = 2) (x = ?, y = 2) (x = ?, y = 4) (x = 3, y = 2) (x = 3, y = 4) (x = 1, y = 4) (x = 5, y = 4) (x = 1, y = 4) (x = 5, y = 4)

Another Example Assume each C statement is atomic Thread AThread Bj = 0; while (j -10) { ++j; --j;} cout << “A wins”;cout << “B wins”;

So… Who wins? Can the computation go on forever? Race conditions occur when threads share data, and their results depend on the timing of their executions… The take home point: sharing data in threads can cause problems, we need some mechanism to deal with such situation.