






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Notes; Professor: Palsetia; Class: DIG SYSTEM ORG & DESIGN; Subject: Computer & Information Technology; University: University of Pennsylvania; Term: Spring 2008;
Typology: Study notes
1 / 10
This page cannot be seen from the preview
Don't miss anything!







2
CIT 595
¾
Prevent overloading of system with too many children
3
CIT 595
4
CIT 595
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?
For child, fork() return value is 0
For parent, fork() return value is the PID of the child
fork() returns -1 if error occurred
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
pid_t wait(int *)
¾
8
CIT 595
Process Termination
exit()
forces the current process to terminate
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
New, Ready, Running, Waiting and Terminated
Extending Thread class
Implementing the Runnable interface
14
CIT 595
Sharing Address Space
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
E.g. Printer driver consumed data before print program produced it
15
CIT 595
Threading Example
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
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
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^
Synchronization can be conceptualized as
locking
mechanism
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
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
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
26
CIT 595
Thread 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
If lock is already locked the calling thread is blocked
If lock is not locked the calling thread acquires it
returns 0 on success
27
CIT 595
Mutex (contd..)
Declare variables as globals i.e. outside all methods
For synchronization:pthread_mutex_lock(&myMutex)
//critical section codepthread_mutex_unlock(&myMutex)
After all work is done, need to destroy them
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
Idea is one thread wait until a certain condition is true
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^
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
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
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
Before actually giving credit check to see if financialsafe
Example with Single Resource class
38
CIT 595
Banker’s Algorithm
To complete a process P
i , check for all resource class R
k
Total_resource
k
k
=
Max_need
i,k
i,k
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