© Janice Regan, CMPT 300, May 2007
0
CMPT 300Introduction to OperatingSystems
Operating Systems
Processes and Threads
 © Janice Regan, CMPT 300, May 2007
1
What is a process?
A process (active entity) is a program (staticentity) in execution, and includes
An address space, an area in memory (memorylocation x to y) containing
List of instructions
Any required data
The stack for the program
Registers
Other information (includes resources used, status ofI/O )
 © Janice Regan, CMPT 300, May 2007
2
Multiprocessing shares memory
When multipleprocesses are sharingthe CPU the memory isshared between them
Each process can onlyaccess it’s own area ofmemory (programimage, stack, …)
Pointers (stored inregisters) give the baseaddress and the lengthor end address. (shownhere in # of words)
Process C
Process A
Process B
Dispatcher
250
10000
7000
5000
4000
1000
 © Janice Regan, CMPT 300, May 2007
3
Processes/Threads
A process groups all resources needed to execute a program
Our OS switches between processes and otherwise managesprocesses, this incurs a significant overhead for each process
Processes are useful for encapsulation and security.
They cannot access each others memory space
The resources they use are protected from otherprocesses
This can be useful when processes are competing forresources (different owners who want optimal turnaround)
However, sometimes we want programs to be able to interactand cooperate and even share memory space when they run,(controlled by the same user, cooperating with each other).The process model does not allow this.
Path of Execution
A path of execution can be thought of as alist of instructions in order they areactually executed when a particularprocess executes.
Two different processes running the sameprogram can have different threads ofexecution
A thread follows a particular path ofexecution through a program
 © Janice Regan, CMPT 300, May 2007
4
 © Janice Regan, CMPT 300, May 2007
5
What is a thread?
A “lightweight process”
Each thread has its own program image
Program counter, registers
Stack (path of execution), automatic data
State
Each thread in a particular process shares
Program text, Global variables
Files and other communication connections
State (different from process state)
What is shared
6
REGISTERS
STACK
IncludesAutomaticvariables
User addressspace
Code
Globalvariables
Heap
Staticvariables
 © Janice Regan, CMPT 300, May 2007
Processcontrol block
Process
Thread 1
Thread 2
Thread 3
Thread ocntrolblock
Thread controlblock
Thread controlblock
REGSITERS
STACK
IncludesAutomaticvariables
REGISTERS
STACK
IncludesAutomaticvariables
Shared
 © Janice Regan, CMPT 300, May 2007
7
Resource ownership
Separate the two main characteristics of a process,Resource ownership/management andScheduling/execution.
Resource ownership: Address space holding aprocess image (program, data, state stored inprocess control block), main memory, connectionsto I/O devices, other hardware devices and otherprocesses (also stored in process control block)
Owned by a process
Shared by a thread
 © Janice Regan, CMPT 300, May 2007
8
Scheduling, execution
Separate the two main characteristics of a process,Resource ownership/management andScheduling/execution.
Scheduling/dispatching/execution
Program counter, registers, stack, locallydeclared  (automatic variables) variables ownedby each thread within a process
Follows an execution path through the programimage (trace through the code)
Execution path is unique to each process, andto each thread within a process
 © Janice Regan, CMPT 300, May 2007
9
Multithreading: advantages
Multithreading: The ability of the operatingsystem to support more than oneconcurrent thread of execution within anygiven process
Increases efficiency over using multipleprocesses because
Fewer process context switches (using shared image)
Less thread context to save (program counter, localthread specific variables, thread state)
Takes less time to create/terminate a thread than aprocess (less to copy)
 © Janice Regan, CMPT 300, May 2007
10
Multithreading: disadvantages
Sharing increases possibility of synchronizationproblems
Each thread can modify all variables in the memoryimage (but cannot control order modifications aredone)
All files and other communication connections areshared.  Reading in one thread, moves readpointer
Suspending a process means suspending severalthreads to allow the image to be swapped
If you fork a multithreaded process, what happens?
 © Janice Regan, CMPT 300, May 2007
11
When threads are useful
Multiprocessor systems (simultaneous execution ofdifferent threads on multiple processors)
Foreground (display and input) and background work(using a word processor, spreadsheet …)
Asynchronous processing (timed save in a wordprocessor, I/0 processing in background …)
Efficiency advantages of multiprocessing within onprocess (one thread blocked, run another)
Modularization: different threads in the process takingcare of different modularized tasks (I/0 from/to varioussources/destinations …)
Good examples in your text
 © Janice Regan, CMPT 300, May 2007
12
Implementing threads
Two main approaches to implementation
User level threads (POSIX Pthreads)
Thread management is the responsibility of the user and occurscompletely in user mode.
Thread scheduling is user controlled, you can choose the best wayto schedule your own threads
Blocking system calls or page faults block all threads (not just one)must wrapper the call so thread is not blocked if device is busy
Cannot take advantages of multiprocessors
Kernel level threads (Windows, newer Linux releases)
All thread management is done by the kernel
Requires mode switch to kernel to move between threads
API  to the kernel thread facility provides users access throughsystem calls
O/S dependent
Process and Thread States
We have discussed the possible states of aprocess (running, blocked, ready, … ).
Each thread in a process can have its own state.The states have the same names but we mustremember that they refer to only one thread
Consider a process that is in the running state. Ifthat process has multiple threads only one of itsthreads will be in the running state, the others willbe in blocked state or in ready state
 © Janice Regan, CMPT 300, May 2007
13
User Level Threads
 © Janice Regan, CMPT 300, May 2007
14
User Space
Kernel Space
T1
P
T1
T2
T3
P
ThreadLibrary
 © Janice Regan, CMPT 300, May 2007
15
User level threads
The application does the thread management in userspace with the help of a thread library
The kernel is not aware that threads are being used
An application begins as a process with a single thread.
The application keeps its own thread table to keep trackof all threads it has created using the library routinethread_create()
The application must use thread_yield() to ask thescheduler (library) to switch to the another thread
No context switch or interrupt are needed (fast)
Cannot let the OS scheduler manage sharing between threadsbecause the OS (kernel level) does not know threads exist
Some possible situations
The process is in running state, onethread yields to another thread in thesame process
The process is in ready state, one of theprocess’s threads is in running state
The process is blocked in blocked state,one of the process’s threads is in runningstate.
 © Janice Regan, CMPT 300, May 2007
16
user –level thread multiprocessing
The threaded application starts as a process containinga single thread. The process is in the running state.
The application uses the user-level thread library tocreate additional threads
When thread A begins to run it will enter the runningstate. Thread A will continue until it calls thread_yield()
When thread_yield() executes it will place Thread A intothe ready state,  place thread B into the running state(formerly in waiting state) and start running thread B
The process is still in the running state
 © Janice Regan, CMPT 300, May 2007
17
User level threads: timesharing
The threaded application starts as a process containing a singlethread. The process is in the running state.
The application uses the user-level thread library to createadditional threads
Thread A (in process 1) has been executing for one processtimesharing quantum and the timer interrupt has transferredcontrol to the kernel.
The kernel does not know about the threads, it saves the contextof process 1 and moves process 1 to ready state, and startsexecuting process 2
Thread A is still in running state even though process 1 is inready state
 © Janice Regan, CMPT 300, May 2007
18
User level threads:  blocking
The threaded application starts as a process containing asingle thread. The process is in the running state.
The application uses the user-level thread library to createadditional threads
When thread A begins to run it will enter the running state.Thread A makes an I/O system call.
Control is transferred to the kernel which blocks the process
Remember the kernel does not know about the threads
Thread A is still in state running, even though the processis in state blocked
It is not possible to run any part (any thread) of the blocked process
 © Janice Regan, CMPT 300, May 2007
19
User level threads: advantages
The process does not have to switch tokernel mode to do thread management
Scheduling is implemented by theapplication (using the thread library) soscheduling can be application specific
User level thread libraries can be portable(can run on more than one OS)
 © Janice Regan, CMPT 300, May 2007
20
User level: disadvantages
When one thread makes a system call whichcauses it to be blocked, the entire process isblocked  (use jacketing to mitigate)
A multithreaded application does not benefitfrom multiprocessing or time sharing.  (theseoccur on a per process basis)
When a multithreaded process calls fork()should some or all threads be duplicated?
Not a simple question
 © Janice Regan, CMPT 300, May 2007
21
Jacketing
Convert blocking system calls to non-blockingsystem calls
Write a jacket routine that checks to see if theblocking devise is presently busy
If the devise is busy and would block control ispassed to a different thread. Otherwise execute therequest
When control returns from the other thread repeatthe previous step
Must have a system call to check if a blocking device is busy(select)
 © Janice Regan, CMPT 300, May 2007
22
Kernel-Level Threads
 © Janice Regan, CMPT 300, May 2007
23
User Space
Kernel Space
T1
P
T1
T2
T3
P
Kernel-level threads
Kernel maintains process control blocks describing eachprocess and thread control blocks describing eachthread
Threads from the same process can be scheduledindependently.  Scheduling can be done for threadsrather than just for processes.
If one thread is blocked, the other threads in the processare not blocked
Switching threads requires a system call and is thereforeless efficient
 © Janice Regan, CMPT 300, May 2007
24
25
Hello world  for threads
Process to be executed by each threadthat is created. When function returnsthread terminates
void *hola(void * arg)
{
  int myid=*(int *) arg;
  printf("Hello, world, I'm %d\n",myid);
  return arg;
}
Author: Mark Hays <hays@math.arizona.edu>
  http://math.arizona.edu/~swig/documentation/pthreads/
Creating Threads
pthread_t threads[NTHREADS];                /* holds thread info */
 int ids[NTHREADS];                                  /* holds thread args */
for (worker=0; worker<NTHREADS; worker++) {
    ids[worker]=worker;
    if ( errcode = pthread_create (&threads[worker],
       NULL,                    /* default thread attributes */
       hola,                       /* start routine             */
       &ids[worker])) {
  errexit(errcode,"pthread_create");
    }
  }
26
Author: Mark Hays <hays@math.arizona.edu>
  http://math.arizona.edu/~swig/documentation/pthreads/
Waiting for threads to terminate
for (worker=0; worker<NTHREADS; worker++) {
    /* wait for thread to terminate */
    if (errcode=pthread_join(threads[worker],(void *) &status)) {
      errexit(errcode,"pthread_join");
    }
    /* check thread's exit status and release its resources */
    if (*status != worker) {
      fprintf(stderr,"thread %d terminated abnormally\n",worker);
      exit(1);
    }
  }
27
Author: Mark Hays <hays@math.arizona.edu>
  http://math.arizona.edu/~swig/documentation/pthreads/