Lecture Notes 13
Lecture Notes 13
CS 3377
1
Reading for Week 11 and 12
Chapter 8 of Advacned Programming in
the UNIX Environment Stevens and
Rago. (Week 11) Process Control
Chapter 11 of Advacned Programming in
the UNIX Environment Stevens and
Rago. (Week 12) Threads
2
Agenda
UNIX Process Creation and Management
Threads: Pthreads
3
CPU Process Switching by OS
4
Silberschatz, Galvin, and Gagne©1999
Process-based Operating System
5
Unix Process State Transition Diagram
Sleep = Blocked
6
UNIX Process Creation
Every process, except process 0, is created by
the fork() system call
◼ fork() allocates entry in process table and assigns a
unique PID to the child process
◼ child gets a copy of process image of parent: both
child and parent share the same code following
fork(), different data
◼ but fork() returns the PID of the child to the parent
process and returns 0 to the child process
◼ Optional Exec() system call can be used after a
fork to replace the process’ memory space with a
new program
7
UNIX Process Creation
Parent process can wait() for
completion of child
◼ The child process can pass data back to
parent via exit() call, picked up by parent
via the wait().
◼ Terminated child is a “zombie” if parent
does not wait() for it
8
UNIX System Processes
9
Unix Tree of Processes
11
Wait functions
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int* status_ptr,
int options)
◼ Waits for completion of a particular child
process
pid_t wait(int* status_ptr)
◼ Waits for any one child to terminate
pid_t getpid(void)
◼ Returns process ID
pid_t getppid(void) (parent ID)
12
Processes on typical Solaris
Process Creation
Copyright © 2010,
Elsevier Inc. All rights
Reserved
Processes and Threads
A process is an instance of a running (or
suspended) program.
Threads are analogous to a “light-
weight” process.
In a shared memory program a single
process may have multiple threads of
control.
Copyright © 2010,
Elsevier Inc. All rights
Reserved
Logical View of Threads
Threads are created within a process
22
Threads
Processes with a single thread of control can
perform one task at a time
Management of multiple threads of control
essential now for concurrent execution of tasks
Most modern desktop and notebook computers
have multiple cores
What is multiple threads of control? →
23
Multiple Threads of Control
Most modern applications are developed as a
separate process with several threads of control.
◼ Number of separate ‘tasks’ that are part of
the application can be executed concurrent
with other tasks.
◼ Example: Word processor
Echoing keystrokes
Undertaking styling formatting
Checking and doing automatic correction
◼ If these tasks had to be executed
sequentially, performance would be
unbearable or simply would not be done thus
reducing the overall quality of, say, a
document.
Multiple Threads of Control
Process Creation:
◼ Process creation is time consuming
◼ Way of doing business before we used threads.
Multiple threads for doing disjoint tasks concurrently
Solution is to have the server create a single thread that
‘listens’ for new requests for service.
When received, server creates a thread to service the
request.
Examples:
◼ RPCs are multi-threaded
◼ Kernels are multi-threaded
Single and Multithreaded Processes
28
Multithreading
Performing multiple threads of execution in
parallel
◼ Replicate registers, PC, etc.
◼ Fast switching between threads
Fine-grain multithreading
◼ Switch threads after each cycle
◼ Interleave instruction execution
◼ If one thread stalls, others are executed
Coarse-grain multithreading
◼ Only switch on long stall (e.g., L2-cache miss)
◼ Simplifies hardware, but doesn’t hide short stalls (eg,
data hazards)
29
Simultaneous Multithreading
In multiple-issue dynamically scheduled
processor
◼ Schedule instructions from multiple threads
◼ Instructions from independent threads execute when
function units are available
◼ Within threads, dependencies handled by scheduling
and register renaming
Example: Intel Pentium-4 HT
◼ Two threads: duplicated registers, shared function
units and caches
30
Multithreading Example
31
Shared Memory Programming
32
Overview of POSIX Threads
POSIX: Portable Operating System Interface
for UNIX
◼ Interface to Operating System utilities
PThreads: The POSIX threading interface
◼ System calls to create and synchronize threads
◼ In CSIL, compile a c program with gcc -lpthread
PThreads contain support for
◼ Creating parallelism and synchronization
◼ No explicit support for communication, because
shared memory is implicit; a pointer to shared data is
passed to a thread
33
Unix Processes vs. Pthreads
C function for starting a thread
pthread.h
One object for
each thread.
pthread_t
int pthread_create (
pthread_t* thread_p /* out */ ,
const pthread_attr_t* attr_p /*
in */ ,
void* (*start_routine ) ( void ) /*
in */ ,
void* arg_p /* in */ ) ; Copyright © 2010,
Elsevier Inc. All rights
Reserved
A closer look (1)
int pthread_create (
pthread_t* thread_p /* out */ ,
const pthread_attr_t* attr_p /*
in */ ,
void* (*start_routine ) ( void ) /*
in */ ,
void* arg_p /* in */ ) ;
We won’t be using, so we just pass NULL.
Copyright © 2010,
Elsevier Inc. All rights
Reserved
A closer look (2)
int pthread_create (
pthread_t* thread_p /* out */ ,
const pthread_attr_t* attr_p /*
in */ ,
void* (*start_routine ) ( void ) /*
in */ ,
void* arg_p /* in */ ) ;
Pointer to the argument that should
be passed to the function start_routine.
The function that the thread is to run.
Copyright © 2010,
Elsevier Inc. All rights
Reserved
pthread_create
Prototype:
void* thread_function ( void* args_p ) ;
Void* can be cast to any pointer type in C.
So args_p can point to a list containing one
or more values needed by thread_function.
Similarly, the return value of thread_function
can point to a list of one or more values.
Copyright © 2010,
Elsevier Inc. All rights
Reserved
Wait for Completion of Threads
pthread_join(pthread_t *thread, void
**result);
◼ Wait for specified thread to finish. Place exit
value into *result.
We call the function pthread_join once
for each thread.
A single call to pthread_join will wait for
the thread associated with the pthread_t
object to complete.
Copyright © 2010,
Elsevier Inc. All rights
Reserved
Example of Pthreads
#include <pthread.h>
#include <stdio.h>
void *PrintHello(void * id){
printf(“Thread%d: Hello World!\n", id);
}
43
The Pthreads API
Thread management: The first class of
functions work directly on threads - creating,
terminating, joining, etc.
Semaphores: provide for create, destroy,
wait, and post on semaphores.
Mutexes: provide for creating, destroying,
locking and unlocking mutexes.
Condition variables: include functions to
create, destroy, wait and signal based upon
specified variable values.
44
Thread Creation
pthread_create (tid, attr, start_routine, arg)
It returns the new thread ID via the tid
argument.
The attr parameter is used to set thread
attributes, NULL for the default values.
The start_routine is the C routine that the thread
will execute once it is created.
A single argument may be passed to
start_routine via arg. It must be passed by
reference as a pointer cast of type void.
45
Thread Termination and Join
pthread_exit (value) ;
This Function is used by a thread to
terminate. The return value is passed as a
pointer.
int i;
Thread
handles
for(i=0;i<NUM_THREADS;i++)
{ Handle of the created
pthread_create(&threads[i], 0, HelloWorld, thread
(void *)i);
}
pthread_exit(0);
return 0;
} Address of
Argument to the function 47
start function
Simple pthread hello
#include <pthread.h>
#include <stdio.h>
#define THREADS 4
/* the function called for each thread */
void* f(void* data) {
printf("Hello from a thread!\n");
pthread_exit(NULL);
}
int main ( ) {
/* an array of threads */
pthread_t threads[THREADS];
/* start all of the threads */
int t;
for (t = 0; t < THREADS; t++) {
pthread_create(&threads[t], NULL, f, NULL);
}
pthread_exit(NULL);
} 48
Pthread hello with thread id arg
49
Example Compiling a Pthread program
Copyright © 2010,
Elsevier Inc. All rights
Reserved