Operating System Processes versus Threads - Lecture Slides | CIT 595, Study notes of Computer Science

Material Type: Notes; Professor: Palsetia; Class: DIG SYSTEM ORG & DESIGN; Subject: Computer & Information Technology; University: University of Pennsylvania; Term: Spring 2008;

Typology: Study notes

Pre 2010

Uploaded on 03/28/2010

koofers-user-l5j
koofers-user-l5j 🇺🇸

5

(1)

8 documents

1 / 10

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
Operating System
Processes vs. Threads
CIT 595
Spring 2008
2
CIT 595
Process Creation
A process can create several other process a.k.a child or
sub processes
Exploit the ability of the system to concurrently execute
E.g. gcc program invokes different processes for the compiler,
assembler, and linker
Each process could get its resources directly from OS
Can restrict resources to subset of parent’s process
¾Prevent overloading of system with too many children
The new process gets its own space in memory
Parent and child processes address space are still different
Because parent and child are isolated, they can
communicate only via system calls
3
CIT 595
Process Creation Ability
OS usually provide a mechanism for process creation
and termination via system calls
Programmers usually access these system calls via
application interface (API) / library
The standard C library provides a set of convenient
wrapper functions for most frequently used system
calls
<unistd.h>
<sys/type.h>
pid_t getpid(void) ; return PID of the caller
pid_t getppid(void); return PID of the caller’s parent
4
CIT 595
Process Creation in Unix
Process creation is done using fork() provided in
<unistd.h>
Child process is exact clone of the parent but with it’s
own copy
int main(){
printf(“Hello\n”);
fork();
printf(“Bye\n”);
return 0;
}
child starts running as soon as
fork() return
Hello is printed once
Bye is printed twice
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Operating System Processes versus Threads - Lecture Slides | CIT 595 and more Study notes Computer Science in PDF only on Docsity!

Operating System

Processes vs. Threads

CIT 595

Spring 2008

2

CIT 595

Process Creation

A process can create several other process a.k.a child orsub processes

„

Exploit the ability of the system to concurrently execute

„

E.g.

gcc

program invokes different processes for the compiler,

assembler, and linker

Each process could get its resources directly from OS

„

Can restrict resources to subset of parent’s process

¾

Prevent overloading of system with too many children

The new process gets its own space in memory

„

Parent and child processes address space are still different

Because parent and child are isolated, they cancommunicate only via system calls

3

CIT 595

Process Creation Ability

OS usually provide a mechanism for process creationand termination via system calls

Programmers usually access these system calls viaapplication interface (API) / library

The standard C library provides a set of convenientwrapper functions for most frequently used systemcalls

<unistd.h><sys/type.h>pid_t getpid(void) ; return PID of the callerpid_t getppid(void); return PID of the caller’s parent

4

CIT 595

Process Creation in Unix

Process creation is done using

fork()

provided in

<unistd.h>

Child process is exact clone of the parent but with it’sown copy

int main(){

printf(“Hello\n”);fork();printf(“Bye\n”);return 0;

child starts running as soon asfork() return

Hello is printed once

Bye is printed twice

5

CIT 595

Example of Process Creation using C

//includes not shownint main(){

pid_t pid;int status;pid_t s;/* fork another process /pid = fork();if (pid < 0) { / error occurred */

fprintf(stderr, "Fork Failed");exit(-1);

} else if (pid == 0) { /* child process */

//Overlay address space with UNIX command "ls"

printf("child pid = %d\n", getpid());if(execl("/bin/ls", "ls", "-la", NULL) < 0){

printf("Command not found\n");exit(1); }

exit(0);

}

else { /* parent process */

/* parent will wait for the child to complete */

printf("#####I am the parent#######\n");

s = wait (&status);if(s != -1) printf("Parent detect child

process # %d is done\n", s);

} return 0;

}

6

CIT 595

Make child do something useful?

„

After fork which process is parent? child? pid_t fork(void);

„

For child, fork() return value is 0 „

For parent, fork() return value is the PID of the child „

fork() returns -1 if error occurred

„

To make child do something overload its address space withwhat you want it do

„

Use

exec()

system call (and its variants)

„

E.g. int execl(const char *path, const char *arg, ...); „

Args to exec are

¾

location of the executable code ¾

Array of string pointers

„

There are many variations on exec

¾

See man pages for execl() and execv

„

If error occurred then returns -

7

CIT 595

Parent Waiting on child to complete

Often a process will have nothing do until its childterminates

„

E.g. what the unix shell usually does when you type a newcommand

pid_t wait(int *)

„

Blocks parent until child terminates

„

On success, returns the pid of the child that exited or -1 if erroroccured

„

Once the child exits, the integer value reference (passed towait) is filled in with the particular status

¾

The parent then can use this status to do something

„

Other variation on wait as well

8

CIT 595

Process Termination

exit()

forces the current process to terminate

„

Is also automatically called when the process ends

OS passes the child’s exit status to the parent andthen discards the process „

On discarding the process all the resources such asmemory and I/O are de-allocated

13

CIT 595

Process and Threads

„

Like process states, threads also have states:

„

New, Ready, Running, Waiting and Terminated

„

Like processes, the OS will switch between threads (even ifthough they belong to a single process) for CPU usage

„

Like process creation, thread creation is supported by APIs

„

Java Threads may be created by:^ „

Extending Thread class „

Implementing the Runnable interface

„

In C, threads are created using functions in <pthread.h> library

14

CIT 595

Sharing Address Space

„

Sharing address space requires only one copy of code or data inmain memory

„

E.g.1: 2 processes share the same library routine (code) „

E.g.2: A print program produces characters and that is consumed byprinter driver (two processes sharing data) „

E.g.3: Threads within a process share (global) data section

„

As long as shared data is not being modified there is no problem

„

But concurrent access to shared data that modify the value of thedata can lead to

data inconsistency

„

E.g. Printer driver consumed data before print program produced it

15

CIT 595

Threading Example

class Counter {

private int c = 0;public void increment() {c++;} public void decrement() {

c--;

} public int value() {

return c;

„

If a Counter object isreferenced from multiplethreads

„

There will be interferencebetween threads when 2operations (increment anddecrement), running indifferent threads, but actingon the same data (i.e. c)

„

This means that the twooperations consist of multiplesteps, and the sequences ofsteps overlap.

16

CIT 595

Threading Example (contd..)

Remember that single expression “c++” can be decomposed into three steps:1.

Retrieve the current value of c.

Increment the retrieved value by 1.

Store the incremented value back in c. „

The same applies for c--

17

CIT 595

Threading Example (contd..)

Suppose Thread 1 invokes increment at about thesame time Thread 2 invokes decrement „

In reality OS is going to switch between Thread 1 and 2

If the initial value of c is 0, their interleaved actionsmight follow this sequence:

Thread 1: Retrieve c

Thread 2: Retrieve c

Thread 1: Increment retrieved value; result is 1

Thread 2: Decrement retrieved value; result is -

Thread 1: Store result in c; c is now 1

Thread 2: Store result in c; c is now -

18

CIT 595

Race Condition

In previous example, Thread 1's result is lost, overwritten by Thread 2

„

Many different interleaving can result in different value of “c”

A situation where several process/threads access and manipulate the same data concurrently and theoutcome of the execution depends on the particularorder in which the access takes place is known as Race Condition

19

CIT 595

Synchronization

To avoid race conditions, need to guarantee exclusiveaccess to the shared data at any point in time „

Synchronization is achieved by^ „

Request entry to critical section (regions of code that maychange shared data)

„

Access (shared) data in critical section

„

Request exit from critical section

Synchronization can be conceptualized as

locking

mechanism

„

When a thread/process is in critical-section, the region islocked for others

„

Only can enter critical section if lock is open

20

CIT 595

Implementing Synchronization

The lock state is implemented by a memory location „

The location contains value 0 if the lock is unlockedand 1 if the lock is locked „

This is e.g. with two threads/processes can be furtherexpanded to multiple threads/processes „

The update to this memory location is atomic (nointerruptions) and is guaranteed by the OS

25

CIT 595

Thread join

„

Causes the calling thread to wait for another thread to terminate

„

Just like wait() for processes

¾

Parent process do not have to wait for children

„

For threads it important as we run the risk of executing an exit (reachend of main) which will terminate the process and all threads beforethe threads have completed

„

int pthread_join(pthread_t thread, void ** value_ptr)

„

thread

is the id of the thread to wait on

„

value_ptr

is the value given to

pthread_exit()

by the terminating thread

„

returns 0 to indicate success

„

Usuage

void * return_val;….//after code creating threadsif(pthread_join(worker_thread, &return_val)){

printf(“Error while waiting on thread\n”);exit(1);

26

CIT 595

Thread mutex

„

Mutex is short for mutual exclusion

„

Provides lock mechanism for shared data

„

To create a mutex

*int pthread_mutex_init(pthread_mutex_t mutex, pthread_mutexattr_t * attr)

„

mutex

is the lock (of type pthread_mutex_t)

„

attr

is the lock attributes ¾

NULL by default

„

To lock:

int pthread_mutex_lock(pthread_mutex_t *mutex)

„

If lock is already locked the calling thread is blocked „

If lock is not locked the calling thread acquires it „

returns 0 on success

„

To Unlock:

pthread_mutex_unlock

27

CIT 595

Mutex (contd..)

Declare variables as globals i.e. outside all methods

„

E.g. pthread_mutex_t myMutex;

For synchronization:pthread_mutex_lock(&myMutex)

//critical section codepthread_mutex_unlock(&myMutex)

After all work is done, need to destroy them

„

pthread_mutex_destroy (&myMutex);

See example p2.c

28

CIT 595

Cond and Wait

If we want one thread to signal an event to another weneed to use Conditional variables

„

pthread_cond_t condVariable

Idea is one thread wait until a certain condition is true

„

Test condition

„

If not true, calls pthread_cond_wait(..) to block until it is

Another thread makes the condition true and callpthread_cond_signal(…) to unblock the thread waiting „

To avoid race conditions, the conditional variable must be use a mutex

29

CIT 595

Example

„

Signalling thread pthread_mutex_lock(&mutex);flag =1;pthread_cond_signal(&condition);pthread_mutex_unclock(&mutex); „

condition is conditional variable

„

type pthread_cond_t

„

mutex is mutex variable

„

type pthread_mutex_t

„

Waiting thread pthread_mutex_lock(&mutex);if(flag == 0)

pthread_cond_wait(&condition,&mutex); pthread_mutex_unlock(&mutex) „^

Wait will automatically release themutex while it waits „

After signal is received and thread isawakened,

mutex

will be automatically

locked for use by the thread. „

Programmer is then responsible forunlocking

mutex

when the thread is

finished with it

30

CIT 595

Deadlock in Resource Sharing Environment „

A

deadlock

occurs when 2 or more processes/threads

permanently block each other by each having a lockon a resource which the other tasks are trying to lock „

Deadlock can occur due to^ „

Locks: Waiting to acquire locks on resources, such as objects,pages etc.

„

Sharing resources such as I/O devices printer, disks etc.

31

CIT 595

Deadlock High-Level View

Task (thread/process) T1 has a lock onresource R1 (indicated by the arrow fromR1 to T1) and has requested a lock onresource R2 (indicated by the arrow fromT1 to R2).

„

Task T2 has a lock on resource R2 andhas requested a lock on resource R

„

Because neither task can continue until aresource is available and neither resourcecan be released until a task continues, adeadlock state exists

32

CIT 595

Deadlock Handling

„

OS must also monitor or avoid deadlock

„

Monitor (more practical approach):^ „

Another service routine that periodically goes and checks on waitingtasks „

If deadlock is determined, then

¾

Abort all processes/threads within that are deadlock – expensive ¾

Abort one process at a time till deadlock is cycle is eliminated

„

Avoidance^ „

By not explicitly over allocating resources „

However this requires prior knowledge of total resources needed byeach task – not practical „

Difficult but many algorithms are proposed

¾

E.g. Banker’s Algorithm

37

CIT 595

Bankers Algorithm

Modeled after banker that gives credit to customers „

Idea is that not all customers will need their maximumcredit immediately

„

Reserve lesser units than the total need

Before actually giving credit check to see if financialsafe „

Example with Single Resource class

„

System contains 10 units of resource class

„

Max Need for P1 = 8, P2 = 7, P3 = 5

„

Current Allocation for (P1 =3, P2 = 1, P3 = 3)

„

If process P1 makes request for one more resource unit i.e.(1, 0, 0) is the system in safe state?

38

CIT 595

Banker’s Algorithm

To complete a process P

i , check for all resource class R

k

Total_resource

k

  • Total_allocated

k

=

Max_need

i,k

  • Allocated_resources

i,k

„

Total_Allocated =

(Allocated_resources

i,k

If satisfied, it simulates completion of Process P

i^

and

release of all resources allocated to it by updatingTotal_allocated

k

for each R

k

P1’s request for one resource unit leads system into safestate „

Sequence P3, P1, P