CS 111 Lecture 7 4/24/2012

By Sheng Ta Li and Dong Woo Jung

Table of Contents


Threads VS Processes

A process contains multithreads.

Pros of using threads:

Cons of using threads:

POSIX threads

 int pthread_create(pthread_t *ID, const pthread_t *attr, void*(*f)(void*), void*status); 
 int pthread_join(pthread_t ID, void *status); 
 int pthread_exit(void *status); 

How to control threads?

Typically n threads > n CPUS (We are going to have more threads running than CPUS)

There are two approches

  1. A) Cooperative multithreading (ex old Mac OS)

  2. B) Preemptive multithreading

Cooperative multithreading

-each thread must yield every now & then.( no loops without yielding)

State of a thread:

  1. 1. running ( has a CPU)
  2. 2. runnable but not running
  3. 3. blocked waiting for resources R(device, pipe, on thread)
  4. so associated with each resource is a queue of threads waiting for it. ( maintained by a next field in each thread descriptor)

Preemptive multithreading

Timer interrupt for preemptive multithreading

pros: no longer require yield() all over the placecons: threads can no longer assume code without yield() is ¡§safe¡¨(bad for real time)(ie. More race conditions)

Aside on signals

What happen if a signal in middle of syscall?ex) Write(...)

Normal solution

signal delivered only when syscall returns, but this approach is fail because of slow syscalls

Event driven programming (inverse of threads)

aio_read() 
- return right way and schedule a read request.

callback invoked when read is done.

	         for(;;){						wait for event                              						pselect(....)							invoke its callback				}

Pros: fewer race conditions
Cons: one core only

Scheduling problem:

we are scheduling a CPU

scheduling scale

Scheduling metrics(developed for auto manufacturing)

Statistic:

Simple scheduling algorithm : first come first serve (FCFS)

JobArrivalWaitTurnaround
A05d5+d
B124+2d6+2d
C295+3d14+3d
D3413+4d17+4d
Avg.5.5+2.5d10.5+4d

Pros:This favors Long job
Cons:This causes convey effect

Shortest Job First (SJF)

JobArrivalWaitTurnaround
A05d5+d
B124+2d6+2d
C299+4d18+4d
D344+3d8+3d
Avg.4.25+2.5d9.25+2.5d

Pros: no convoys effects
Cons: Starvation
-it was not fair!