程序代写 CMPUT 379 (E.S. Elmallah)

Processes and Threads
1. Introduction
2. A Conceptual Framework
3. Processes in 4.4BSD UNIX

Copyright By PowCoder代写 加微信 powcoder

4. Process Creation
5. Threads
6. Case Study: Threading on Sun Solaris
7. POSIX Threads
CMPUT 379 (E.S. Elmallah)
1. Introduction
 Concurrency in modern operating systems creates a marvelous environment:
CMPUT 379 (E.S. Elmallah)

 It is so, because we can successfully handle dozens of processes:
USER PID %CPU %MEM STAT START TIME
[kflushd] [kswapd] /sbin/mingetty xclock -bw 10 -bg firefox
xterm -sb -sl 500
root 1 0.3 root 2 0.0 root 4 0.0 root 579 0.0 mary 683 0.0 steve 685 0.4 sue 692 0.1
0.7 S 22:40 0:03 0.0 SW 22:40 0:00 0.0 SW 22:40 0:00
0.5 S 2.0 S 18.0 S
22:41 0:00 22:44 0:00 22:44 0:03
22:44 0:01
 Issues to discuss:
o Definition (how to?)
o Process states
o Process data structures
CMPUT 379 (E.S. Elmallah)
 Process Definition (OS- dependent):
o A program executing in some environment
o Program executing: text segment, bss segment, heap, and stack
o Context: shell environment variables, user access privileges, etc.
CMPUT 379 (E.S. Elmallah)
[SR 2/E] 4

 Exercise: How to expand a process’ stack?
 Exercise: Which variables use the stack? Which use the heap?
#include void foo (int n) { int i, a[5], *b;
if (n == 0) return;
b= new int[n];
printf (“foo(%d): &i= %p, a= %p, b= %p \n”, n, &i, a, b); foo(n-1);
int main () { foo(3); }
CMPUT 379 (E.S. Elmallah)
 A possible output:
 Anyway: a process  a program  a job
foo(3): &i= bffff9a4, a= bffff990, b= 80497f0 foo(2): &i= bffff964, a= bffff950, b= 8049800 foo(1): &i= bffff924, a= bffff910, b= 8049810
CMPUT 379 (E.S. Elmallah)

2. A Conceptual Framework
 Now, let’s examine a conceptual framework of
o Process states
o Process data structures (for a process control block (PCB) )
o Process queues  Process states
CMPUT 379 (E.S. Elmallah)
 Process data structures (for a process control block (PCB) )
o Process state – running, waiting, etc
o Program counter – location of instruction to
next execute
o CPU registers – contents of all process- centric registers
o CPU scheduling information- priorities, scheduling queue pointers
o Memory-management information – memory allocated to the process
o Accounting information – CPU used, clock time elapsed since start, time limits
o I/O status information – I/O devices allocated to process, list of open files
CMPUT 379 (E.S. Elmallah)

 Process queues: ready queue and I/O device queues
CMPUT 379 (E.S. Elmallah)
3. Processes in 4.4BSD UNIX
Now, let’s Compare the above components with their counterpart in the 4.4BSD UNIX:
 Process States
o SIDL : intermediate state after creation
(by a fork() system call)
o SRUN : runnable (has enough resources)
o SSLEEP : waiting for an event (e.g., an I/O operation) o SSTOP : stopped (by a signal, or a parent process)
o SZOMB : intermediate state in process termination
CMPUT 379 (E.S. Elmallah)

 A Typical Life Cycle [4.4 BSD]:
CMPUT 379 (E.S. Elmallah)
 Process Data Structures: uses 4 data structures
o Memory Resident : the process struct, the text struct,
o Movable to Disk : the user struct, and the process page table struct.
 The Process Struct
o a table; logically divided into several categories
CMPUT 379 (E.S. Elmallah)

Process data structure [MBKQ 4.4BSD] CMPUT 379 (E.S. Elmallah)
SLOAD SSYS
SOWEUPC process collecting system-call timing information
SWEXIT SPHYSIO SVFORK SLOGIN ·····
process is exiting
process doing physical I/O process resulted from vfork()
a login process
process loaded in main memory
process created by system (e.g., swapper or page daemon)
process is swapped out process is being debugged
user requested that process not be swapped process waiting for page to be retrieved
kernel requires process in memory
Process flags [MBKQ 4.4BSD] CMPUT 379 (E.S. Elmallah)

o pid : unique id. for a process
o p_ppid: unique id. for the parent o p_pgrp: the group id. number:
• a process-group (a job) is a collection of related processes assigned the same process-group identifier.
CMPUT 379 (E.S. Elmallah)
 Example: “cat file | grep uofa | wc”
o killpg(): broadcasted to all processes in the same process-group
CMPUT 379 (E.S. Elmallah)

 The Process Structure Queues
o The run queue : a doubly linked list, organized by the
process-scheduling priority, of runnable processes.
o The sleep queue : a hashing table storing blocked processes waiting for certain events.
 The User struct
o May be swapped out from memory.
o A table; logically divided into several categories:
• The Current Execution State : program counter, registers, status word, stack limits, virtual memory information, etc.
• state related to system calls • accounting information
CMPUT 379 (E.S. Elmallah)
4. Process Creation
 Some initial processes:
the parent of all processes; creates processes from /etc/inittab that causes init to spawn getty
2 kflushd ?
4 kswapd the scheduler process (?) ······
CMPUT 379 (E.S. Elmallah)

 Process Creation o fork()
• spawns a child process with a copy of the parent’s space (text, data, bss, stack, open files, environment variables, etc.)
• returns 0 to the child;
• returns p_pid > 0 to the parent.
o execl() and execv()
• replace the process’ space by a new executable image • cause no change in the p_pid
o Fails if the user (or the system) exhausts the allowed maximum number of processes.
CMPUT 379 (E.S. Elmallah)
 Example 1: fork()
#include #include #include
int main(void) { pid_t pid;
pid = getpid(); for ( ; ; ) {
printf (“Hello, my name is %d! \n”, pid); }
return 0; }
CMPUT 379 (E.S. Elmallah)

 Exercises
o After forking, does the child have access to the
parent’s global variables?
o Can one distinguish the child’s output from the parent’s output visually?
o Can one add code after the fork() call to distinguish the two processes?
 Waiting for a Child
o wait() causes the parent to block until one of its
children changes its status. o See also, waitpid() .
CMPUT 379 (E.S. Elmallah)
o Example 2: fork() and wait()
#include #define NLINES 40
int i, status; pid_t pid;
int main (void) {
} else { /* the parent process */
for (i= NLINES; i > 0; i–) printf (“%d. I am the parent! \n”, i); wait (&status);
} return 0;
pid = fork (); if (pid == 0) {
/* the child process */
for (i=1; i < NLINES; i++) printf ("%d. I am the child! \n", i); CMPUT 379 (E.S. Elmallah)  Process Termination o Normal Termination : execute return() from main, exit() , or _exit() o Abnormal Termination : execute abort(), receive a nasty signal o Normally, a process waits for its children to terminate (the parent receives a signal to this effect): • a zombie is a child that terminates with no waiting parent; • an orphan is a child whose parent has terminated while the child is still running. CMPUT 379 (E.S. Elmallah) 5. Threads  A “traditional” Unix process has one thread of control.  Why introduce multiple threads of control inside a o utilize the power of multiprocessor systems o achieve a higher application concurrency level CMPUT 379 (E.S. Elmallah)  Consider a communication-intensive application (e.g., a server of some sort) o What happens if it awaits a user input? • It blocks, loses its cached code, and may be swapped out to disk. o How to minimize such risk? • Provide an environment where the application has multiple threads with shared memory communication. o Some issues to think about: • Is it OK to share variables and open files? • How to synchronize threads? • Is thread protection an issue? • Who catches the incoming signals? CMPUT 379 (E.S. Elmallah)  Out-of-kernel Solutions (or user-level threads) o Examples: the C-Threads package. Offers different implementations: • coroutines in a single process • separate process for each thread, using inherited shared memory o Disadvantages: • scheduling is difficult to implement: many packages provide non-preemptive scheduling • if a thread takes a page fault (or other trap) all other threads must wait • only a single thread may execute a system call CMPUT 379 (E.S. Elmallah)  What constitutes the “state” of a thread in a process? o Thread ID o Register state (PC, stack pointer, etc.) o Stack o Signal mask o Priority o Thread-local storage • E.g., in Solaris, one may use: #pragama unshared errno; extern int errno; CMPUT 379 (E.S. Elmallah) 6. Case Study: Threading on Sun Solaris  Solaris provides: o Out-of-kernel support: as in typical coroutine packages o kernel support: Light Weight Processes (LWPs) CMPUT 379 (E.S. Elmallah)  Example [Solaris documentation]: thr_create() #define _REENTRANT #include #include #include #include #include
void *athread (void *arg) {
printf (“Thread ID: %2d, arg: %s\n”, (int) thr_self(), (char *) arg) ;
return 0; }
CMPUT 379 (E.S. Elmallah)
int main (int argc, char *argv[]) { int i;
for (i= 0; i < argc; ++i) { int n; n= thr_create (NULL, 0, athread, (void *) argv[i], THR_DETACHED, NULL); if (n) { fprintf (stderr, "thr_create: %s\n", strerror(n) ); exit (1); } thr_exit(0); } CMPUT 379 (E.S. Elmallah) 7. POSIX Threads (pthreads)  POSIX defines an API, not an implementation  Example declarations and functions: o Declarations • #include • pthread_t tid; //thread identifier (int or struct) • pthread_attr_t attr; //thread attributes: e.g., thread
// stack address and size
o Get default attributes
• pthread_attr_init (&attr);
o Create a thread
• pthread_create (&tid, &attr, start_routine, arg)
CMPUT 379 (E.S. Elmallah)
o Exit a thread
• pthread_exit()
o Wait for a thread to exit
• pthread_join (tid, status)
CMPUT 379 (E.S. Elmallah)

 Example: pthreads
#define _REENTRANT
#include , , , , void *athread (void *arg) {
int i; pid_t pthread_t tid;
pid= getpid(); tid= pthread_self();
printf (“Process ID: %d, thread ID: %u (0x%x), arg: %s\n”, (int) pid,
(unsigned int) pthread_self(), (unsigned int) pthread_self(), (char *) arg) ;
CMPUT 379 (E.S. Elmallah)
int main (int argc, char *argv[]) { int i, rval; pthread_t ntid;
for (i= 0; i < argc; ++i) { rval= pthread_create (&ntid, NULL, athread, (void *) argv[i]); if (rval) { fprintf (stderr, "thr_create: %s\n", strerror(rval) ); exit (1); } pthread_exit(0); } CMPUT 379 (E.S. Elmallah)  Questions o If a multi-threaded process forks a child, how many threads should the child inherit? o Discuss the suitability of the following to multi- threaded architectures: (a) use of library routines that returns results in static areas (e.g., errno) (b) use of non-reentrant library routines CMPUT 379 (E.S. Elmallah) 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com