text
stringlengths
1
7.76k
source
stringlengths
17
81
84 INTRODUCTION CHAP. 1 ruining the file system. You can also do the experiment safely in a virtual machine. Note: Do not try this on a shared system without first getting permission from the sys- tem administrator. The consequences will be instantly obvious so you are likely to be caught and sanctions may follow. 36. ...
clipped_os_Page_84_Chunk6301
2 PROCESSES AND THREADS We are now about to embark on a detailed study of how operating systems are designed and constructed. The most central concept in any operating system is the process: an abstraction of a running program. Everything else hinges on this con- cept, and the operating system designer (and student) sh...
clipped_os_Page_85_Chunk6302
86 PROCESSES AND THREADS CHAP. 2 in. If there are multiple disks present, some or all of the newer ones may be fired off to other disks long before the first request is satisfied. Clearly some way is needed to model and control this concurrency. Processes (and especially threads) can help here. Now consider a user PC. ...
clipped_os_Page_86_Chunk6303
SEC. 2.1 PROCESSES 87 a long enough time interval, all the processes have made progress, but at any giv en instant only one process is actually running. A B C D D C B A Process switch One program counter Four program counters Process Time B C D A (a) (b) (c) Figure 2-1. (a) Multiprogramming four programs. (b) Conceptua...
clipped_os_Page_87_Chunk6304
88 PROCESSES AND THREADS CHAP. 2 and the cake ingredients are the input data. The process is the activity consisting of our baker reading the recipe, fetching the ingredients, and baking the cake. Now imagine that the computer scientist’s son comes running in screaming his head off, saying that he has been stung by a b...
clipped_os_Page_88_Chunk6305
SEC. 2.1 PROCESSES 89 example, one background process may be designed to accept incoming email, sleeping most of the day but suddenly springing to life when email arrives. Another background process may be designed to accept incoming requests for Web pages hosted on that machine, waking up when a request arrives to ser...
clipped_os_Page_89_Chunk6306
90 PROCESSES AND THREADS CHAP. 2 program. For example, when a user types a command, say, sort, to the shell, the shell forks off a child process and the child executes sort. The reason for this two- step process is to allow the child to manipulate its file descriptors after the fork but before the execve in order to ac...
clipped_os_Page_90_Chunk6307
SEC. 2.1 PROCESSES 91 Windows. Screen-oriented programs also support voluntary termination. Word processors, Internet browsers, and similar programs always have an icon or menu item that the user can click to tell the process to remove any temporary files it has open and then terminate. The second reason for terminatio...
clipped_os_Page_91_Chunk6308
92 PROCESSES AND THREADS CHAP. 2 per terminal. These processes wait for someone to log in. If a login is successful, the login process executes a shell to accept commands. These commands may start up more processes, and so forth. Thus, all the processes in the whole system be- long to a single tree, with init at the ro...
clipped_os_Page_92_Chunk6309
SEC. 2.1 PROCESSES 93 1 2 3 4 Blocked Running Ready 1. Process blocks for input 2. Scheduler picks another process 3. Scheduler picks this process 4. Input becomes available Figure 2-2. A process can be in running, blocked, or ready state. Transitions be- tween these states are as shown. Four transitions are possible a...
clipped_os_Page_93_Chunk6310
94 PROCESSES AND THREADS CHAP. 2 the interrupt handling and details of actually starting and stopping processes are hidden away in what is here called the scheduler, which is actually not much code. The rest of the operating system is nicely structured in process form. Few real sys- tems are as nicely structured as thi...
clipped_os_Page_94_Chunk6311
SEC. 2.1 PROCESSES 95 Process management Memory management File management Registers Pointer to text segment info Root directory Program counter Pointer to data segment info Wor king director y Program status word Pointer to stack segment info File descriptors Stack pointer User ID Process state Group ID Pr ior ity Sch...
clipped_os_Page_95_Chunk6312
96 PROCESSES AND THREADS CHAP. 2 1. Hardware stacks program counter, etc. 2. Hardware loads new program counter from interrupt vector. 3. Assembly-language procedure saves registers. 4. Assembly-language procedure sets up new stack. 5. C interrupt service runs (typically reads and buffers input). 6. Scheduler decides w...
clipped_os_Page_96_Chunk6313
SEC. 2.1 PROCESSES 97 For the sake of accuracy, it should be pointed out that the probabilistic model just described is only an approximation. It implicitly assumes that all n processes are independent, meaning that it is quite acceptable for a system with fiv e proc- esses in memory to have three running and two waiti...
clipped_os_Page_97_Chunk6314
98 PROCESSES AND THREADS CHAP. 2 We hav e seen this argument once before. It is precisely the argument for hav- ing processes. Instead, of thinking about interrupts, timers, and context switches, we can think about parallel processes. Only now with threads we add a new ele- ment: the ability for the parallel entities t...
clipped_os_Page_98_Chunk6315
SEC. 2.2 THREADS 99 Threads can help here. Suppose that the word processor is written as a two- threaded program. One thread interacts with the user and the other handles refor- matting in the background. As soon as the sentence is deleted from page 1, the interactive thread tells the reformatting thread to reformat th...
clipped_os_Page_99_Chunk6316
100 PROCESSES AND THREADS CHAP. 2 An analogous situation exists with many other interactive programs. For exam- ple, an electronic spreadsheet is a program that allows a user to maintain a matrix, some of whose elements are data provided by the user. Other elements are com- puted based on the input data using potential...
clipped_os_Page_100_Chunk6317
SEC. 2.2 THREADS 101 When the thread blocks on the disk operation, another thread is chosen to run, pos- sibly the dispatcher, in order to acquire more work, or possibly another worker that is now ready to run. This model allows the server to be written as a collection of sequential threads. The dispatcher’s program co...
clipped_os_Page_101_Chunk6318
102 PROCESSES AND THREADS CHAP. 2 reply processed. With nonblocking disk I/O, a reply probably will have to take the form of a signal or interrupt. In this design, the ‘‘sequential process’’ model that we had in the first two cases is lost. The state of the computation must be explicitly saved and restored in the table...
clipped_os_Page_102_Chunk6319
SEC. 2.2 THREADS 103 separate them; this is where threads come in. First we will look at the classical thread model; after that we will examine the Linux thread model, which blurs the line between processes and threads. One way of looking at a process is that it is a way to group related resources together. A process h...
clipped_os_Page_103_Chunk6320
104 PROCESSES AND THREADS CHAP. 2 Thread Thread Kernel Kernel Process 1 Process 2 Process 3 Process User space Kernel space (a) (b) Figure 2-11. (a) Three processes each with one thread. (b) One process with three threads. same global variables. Since every thread can access every memory address within the process’ add...
clipped_os_Page_104_Chunk6321
SEC. 2.2 THREADS 105 of resource management, not the thread. If each thread had its own address space, open files, pending alarms, and so on, it would be a separate process. What we are trying to achieve with the thread concept is the ability for multiple threads of ex- ecution to share a set of resources so that they ...
clipped_os_Page_105_Chunk6322
106 PROCESSES AND THREADS CHAP. 2 address space of the creating thread. Sometimes threads are hierarchical, with a parent-child relationship, but often no such relationship exists, with all threads being equal. With or without a hierarchical relationship, the creating thread is usually returned a thread identifier that...
clipped_os_Page_106_Chunk6323
SEC. 2.2 THREADS 107 a few of the major ones to give an idea of how it works. The calls we will describe below are listed in Fig. 2-14. Thread call Description Pthread create Create a new thread Pthread exit Ter minate the calling thread Pthread join Wait for a specific thread to exit Pthread yield Release the CPU to l...
clipped_os_Page_107_Chunk6324
108 PROCESSES AND THREADS CHAP. 2 a new thread on each iteration, after announcing its intention. If the thread creation fails, it prints an error message and then exits. After creating all the threads, the main program exits. #include <pthread.h> #include <stdio.h> #include <stdlib.h> #define NUMBER OF THREADS 10 void...
clipped_os_Page_108_Chunk6325
SEC. 2.2 THREADS 109 The first method is to put the threads package entirely in user space. The ker- nel knows nothing about them. As far as the kernel is concerned, it is managing ordinary, single-threaded processes. The first, and most obvious, advantage is that a user-level threads package can be implemented on an o...
clipped_os_Page_109_Chunk6326
110 PROCESSES AND THREADS CHAP. 2 the machine happens to have an instruction to store all the registers and another one to load them all, the entire thread switch can be done in just a handful of in- structions. Doing thread switching like this is at least an order of magnitude— maybe more—faster than trapping to the k...
clipped_os_Page_110_Chunk6327
SEC. 2.2 THREADS 111 Somewhat analogous to the problem of blocking system calls is the problem of page faults. We will study these in Chap. 3. For the moment, suffice it to say that computers can be set up in such a way that not all of the program is in main memo- ry at once. If the program calls or jumps to an instruc...
clipped_os_Page_111_Chunk6328
112 PROCESSES AND THREADS CHAP. 2 The kernel’s thread table holds each thread’s registers, state, and other infor- mation. The information is the same as with user-level threads, but now kept in the kernel instead of in user space (inside the run-time system). This information is a subset of the information that tradit...
clipped_os_Page_112_Chunk6329
SEC. 2.2 THREADS 113 When this approach is used, the programmer can determine how many kernel threads to use and how many user-level threads to multiplex on each one. This model gives the ultimate in flexibility. Multiple user threads on a kernel thread User space Kernel space Kernel thread Kernel Figure 2-17. Multiple...
clipped_os_Page_113_Chunk6330
114 PROCESSES AND THREADS CHAP. 2 kernel-user transition. The user-space run-time system can block the synchronizing thread and schedule a new one by itself. When scheduler activations are used, the kernel assigns a certain number of virtual processors to each process and lets the (user-space) run-time system allo- cat...
clipped_os_Page_114_Chunk6331
SEC. 2.2 THREADS 115 call waiting for an incoming message. When a message arrives, it accepts the mes- sage, unpacks it, examines the contents, and processes it. However, a completely different approach is also possible, in which the arrival of a message causes the system to create a new thread to handle the message. S...
clipped_os_Page_115_Chunk6332
116 PROCESSES AND THREADS CHAP. 2 2.2.9 Making Single-Threaded Code Multithreaded Many existing programs were written for single-threaded processes. Convert- ing these to multithreading is much trickier than it may at first appear. Below we will examine just a few of the pitfalls. As a start, the code of a thread norma...
clipped_os_Page_116_Chunk6333
SEC. 2.2 THREADS 117 new scoping level, variables visible to all the procedures of a thread (but not to other threads), in addition to the existing scoping levels of variables visible only to one procedure and variables visible everywhere in the program. Thread 1's code Thread 2's code Thread 1's stack Thread 2's stack...
clipped_os_Page_117_Chunk6334
118 PROCESSES AND THREADS CHAP. 2 The next problem in turning a single-threaded program into a multithreaded one is that many library procedures are not reentrant. That is, they were not de- signed to have a second call made to any giv en procedure while a previous call has not yet finished. For example, sending a mess...
clipped_os_Page_118_Chunk6335
SEC. 2.2 THREADS 119 These problems are certainly not insurmountable, but they do show that just introducing threads into an existing system without a fairly substantial system redesign is not going to work at all. The semantics of system calls may have to be redefined and libraries rewritten, at the very least. And al...
clipped_os_Page_119_Chunk6336
120 PROCESSES AND THREADS CHAP. 2 wants to print a file, it enters the file name in a special spooler directory. Another process, the printer daemon, periodically checks to see if there are any files to be printed, and if there are, it prints them and then removes their names from the di- rectory. Imagine that our spoo...
clipped_os_Page_120_Chunk6337
SEC. 2.3 INTERPROCESS COMMUNICATION 121 never comes. Situations like this, where two or more processes are reading or writ- ing some shared data and the final result depends on who runs precisely when, are called race conditions. Debugging programs containing race conditions is no fun at all. The results of most test r...
clipped_os_Page_121_Chunk6338
122 PROCESSES AND THREADS CHAP. 2 A enters critical region A leaves critical region B attempts to enter critical region B enters critical region T1 T2 T3 T4 Process A Process B B blocked B leaves critical region Time Figure 2-22. Mutual exclusion using critical regions. 2.3.3 Mutual Exclusion with Busy Waiting In this ...
clipped_os_Page_122_Chunk6339
SEC. 2.3 INTERPROCESS COMMUNICATION 123 often a useful technique within the operating system itself but is not appropriate as a general mutual exclusion mechanism for user processes. The possibility of achieving mutual exclusion by disabling interrupts—even within the kernel—is becoming less every day due to the increa...
clipped_os_Page_123_Chunk6340
124 PROCESSES AND THREADS CHAP. 2 while (TRUE) { while (TRUE) { while (turn != 0) /* loop */ ; while (turn != 1) /* loop */ ; cr itical region( ); cr itical region( ); tur n = 1; tur n = 0; noncr itical region( ); noncr itical region( ); } } (a) (b) Figure 2-23. A proposed solution to the critical-region problem. (a) P...
clipped_os_Page_124_Chunk6341
SEC. 2.3 INTERPROCESS COMMUNICATION 125 In 1981, G. L. Peterson discovered a much simpler way to achieve mutual exclusion, thus rendering Dekker’s solution obsolete. Peterson’s algorithm is shown in Fig. 2-24. This algorithm consists of two procedures written in ANSI C, which means that function prototypes should be su...
clipped_os_Page_125_Chunk6342
126 PROCESSES AND THREADS CHAP. 2 The TSL Instruction Now let us look at a proposal that requires a little help from the hardware. Some computers, especially those designed with multiple processors in mind, have an instruction like TSL RX,LOCK (Test and Set Lock) that works as follows. It reads the contents of the memo...
clipped_os_Page_126_Chunk6343
SEC. 2.3 INTERPROCESS COMMUNICATION 127 enter region: TSL REGISTER,LOCK | copy lock to register and set lock to 1 CMP REGISTER,#0 | was lock zero? JNE enter region | if it was not zero, lock was set, so loop RET | retur n to caller; critical region entered leave region: MOVE LOCK,#0 | store a 0 in lock RET | retur n to...
clipped_os_Page_127_Chunk6344
128 PROCESSES AND THREADS CHAP. 2 scheduled while H is running, L never gets the chance to leave its critical region, so H loops forever. This situation is sometimes referred to as the priority inversion problem. Now let us look at some interprocess communication primitives that block in- stead of wasting CPU time when...
clipped_os_Page_128_Chunk6345
SEC. 2.3 INTERPROCESS COMMUNICATION 129 #define N 100 /* number of slots in the buffer */ int count = 0; /* number of items in the buffer */ void producer(void) { int item; while (TRUE) { /* repeat forever */ item = produce item( ); /* generate next item */ if (count == N) sleep( ); /* if buffer is full, go to sleep */...
clipped_os_Page_129_Chunk6346
130 PROCESSES AND THREADS CHAP. 2 While the wakeup waiting bit saves the day in this simple example, it is easy to construct examples with three or more processes in which one wakeup waiting bit is insufficient. We could make another patch and add a second wakeup waiting bit, or maybe 8 or 32 of them, but in principle ...
clipped_os_Page_130_Chunk6347
SEC. 2.3 INTERPROCESS COMMUNICATION 131 system briefly disabling all interrupts while it is testing the semaphore, updating it, and putting the process to sleep, if necessary. As all of these actions take only a few instructions, no harm is done in disabling interrupts. If multiple CPUs are being used, each semaphore s...
clipped_os_Page_131_Chunk6348
132 PROCESSES AND THREADS CHAP. 2 This solution uses three semaphores: one called full for counting the number of slots that are full, one called empty for counting the number of slots that are empty, and one called mutex to make sure the producer and consumer do not access the buffer at the same time. Full is initiall...
clipped_os_Page_132_Chunk6349
SEC. 2.3 INTERPROCESS COMMUNICATION 133 Tw o procedures are used with mutexes. When a thread (or process) needs access to a critical region, it calls mutex lock. If the mutex is currently unlocked (mean- ing that the critical region is available), the call succeeds and the calling thread is free to enter the critical r...
clipped_os_Page_133_Chunk6350
134 PROCESSES AND THREADS CHAP. 2 The mutex system that we have described above is a bare-bones set of calls. With all software, there is always a demand for more features, and synchronization primitives are no exception. For example, sometimes a thread package offers a call mutex trylock that either acquires the lock ...
clipped_os_Page_134_Chunk6351
SEC. 2.3 INTERPROCESS COMMUNICATION 135 really has to. Since switching to the kernel and back is quite expensive, doing so improves performance considerably. A futex consists of two parts: a kernel service and a user library. The kernel service provides a ‘‘wait queue’’ that allows multiple processes to wait on a lock....
clipped_os_Page_135_Chunk6352
136 PROCESSES AND THREADS CHAP. 2 Thread call Description Pthread mutex init Create a mutex Pthread mutex destroy Destroy an existing mutex Pthread mutex lock Acquire a lock or block Pthread mutex tr ylock Acquire a lock or fail Pthread mutex unlock Release a lock Figure 2-30. Some of the Pthreads calls relating to mut...
clipped_os_Page_136_Chunk6353
SEC. 2.3 INTERPROCESS COMMUNICATION 137 Thread call Description Pthread cond init Create a condition var iable Pthread cond destroy Destroy a condition var iable Pthread cond wait Block waiting for a signal Pthread cond signal Signal another thread and wake it up Pthread cond broadcast Signal multiple threads and wake ...
clipped_os_Page_137_Chunk6354
138 PROCESSES AND THREADS CHAP. 2 #include <stdio.h> #include <pthread.h> #define MAX 1000000000 /* how many numbers to produce */ pthread mutex t the mutex; pthread cond t condc, condp; /* used for signaling */ int buffer = 0; /* buffer used between producer and consumer */ void *producer(void *ptr) /* produce data */...
clipped_os_Page_138_Chunk6355
SEC. 2.3 INTERPROCESS COMMUNICATION 139 Monitors have an important property that makes them useful for achieving mutual exclusion: only one process can be active in a monitor at any instant. Moni- tors are a programming-language construct, so the compiler knows they are special and can handle calls to monitor procedure...
clipped_os_Page_139_Chunk6356
140 PROCESSES AND THREADS CHAP. 2 monitor example integer i; condition c; procedure producer( ); ... end; procedure consumer( ); . . . end; end monitor; Figure 2-33. A monitor. waiting on it, the signal is lost forever. In other words, the wait must come before the signal. This rule makes the implementation much simple...
clipped_os_Page_140_Chunk6357
SEC. 2.3 INTERPROCESS COMMUNICATION 141 monitor ProducerConsumer condition full, empty; integer count; procedure insert(item: integer); begin if count = N then wait(full); insert item(item); count := count + 1; if count = 1 then signal(empty) end; function remove: integer; begin if count = 0 then wait(empty); remove = ...
clipped_os_Page_141_Chunk6358
142 PROCESSES AND THREADS CHAP. 2 public class ProducerConsumer { static final int N = 100; // constant giving the buffer size static producer p = new producer( ); // instantiate a new producer thread static consumer c = new consumer( ); // instantiate a new consumer thread static our monitor mon = new our monitor( ); ...
clipped_os_Page_142_Chunk6359
SEC. 2.3 INTERPROCESS COMMUNICATION 143 The producer and consumer threads are functionally identical to their count- erparts in all our previous examples. The producer has an infinite loop generating data and putting it into the common buffer. The consumer has an equally infinite loop taking data out of the common buff...
clipped_os_Page_143_Chunk6360
144 PROCESSES AND THREADS CHAP. 2 inapplicable. The conclusion is that semaphores are too low lev el and monitors are not usable except in a few programming languages. Also, none of the primitives allow information exchange between machines. Something else is needed. 2.3.8 Message Passing That something else is message...
clipped_os_Page_144_Chunk6361
SEC. 2.3 INTERPROCESS COMMUNICATION 145 At the other end of the spectrum, there are also design issues that are important when the sender and receiver are on the same machine. One of these is perfor- mance. Copying messages from one process to another is always slower than doing a semaphore operation or entering a moni...
clipped_os_Page_145_Chunk6362
146 PROCESSES AND THREADS CHAP. 2 #define N 100 /* number of slots in the buffer */ void producer(void) { int item; message m; /* message buffer */ while (TRUE) { item = produce item( ); /* generate something to put in buffer */ receive(consumer, &m); /* wait for an empty to arrive */ build message(&m, item); /* constr...
clipped_os_Page_146_Chunk6363
SEC. 2.3 INTERPROCESS COMMUNICATION 147 Barrier Barrier Barrier A A A B B B C C D D D Time Time Time Process (a) (b) (c) C Figure 2-37. Use of a barrier. (a) Processes approaching a barrier. (b) All proc- esses but one blocked at the barrier. (c) When the last process arrives at the barri- er, all of them are let throu...
clipped_os_Page_147_Chunk6364
148 PROCESSES AND THREADS CHAP. 2 is to program each process to execute a barr ier operation after it has finished its part of the current iteration. When all of them are done, the new matrix (the input to the next iteration) will be finished, and all processes will be simultaneously re- leased to start the next iterat...
clipped_os_Page_148_Chunk6365
SEC. 2.4 SCHEDULING 149 (a) Original tree. (b) Initialize node X and connect E to X. Any readers in A and E are not affected. X A B E D C D C D C D C D C A B E (c) When X is completely initialized, connect X to A. Readers currently in E will have read the old version, while readers in A will pick up the new version of ...
clipped_os_Page_149_Chunk6366
150 PROCESSES AND THREADS CHAP. 2 2.4.1 Introduction to Scheduling Back in the old days of batch systems with input in the form of card images on a magnetic tape, the scheduling algorithm was simple: just run the next job on the tape. With multiprogramming systems, the scheduling algorithm became more complex because t...
clipped_os_Page_150_Chunk6367
SEC. 2.4 SCHEDULING 151 In addition to picking the right process to run, the scheduler also has to worry about making efficient use of the CPU because process switching is expensive. To start with, a switch from user mode to kernel mode must occur. Then the state of the current process must be saved, including storing ...
clipped_os_Page_151_Chunk6368
152 PROCESSES AND THREADS CHAP. 2 The former are called compute-bound or CPU-bound; the latter are called I/O- bound. Compute-bound processes typically have long CPU bursts and thus infre- quent I/O waits, whereas I/O-bound processes have short CPU bursts and thus fre- quent I/O waits. Note that the key factor is the l...
clipped_os_Page_152_Chunk6369
SEC. 2.4 SCHEDULING 153 respect to how they deal with clock interrupts. A nonpreemptive scheduling algo- rithm picks a process to run and then just lets it run until it blocks (either on I/O or waiting for another process) or voluntarily releases the CPU. Even if it runs for many hours, it will not be forcibly suspende...
clipped_os_Page_153_Chunk6370
154 PROCESSES AND THREADS CHAP. 2 In systems with real-time constraints, preemption is, oddly enough, sometimes not needed because the processes know that they may not run for long periods of time and usually do their work and block quickly. The difference with interactive systems is that real-time systems run only pro...
clipped_os_Page_154_Chunk6371
SEC. 2.4 SCHEDULING 155 done per second than if some of the components are idle. In a batch system, for example, the scheduler has control of which jobs are brought into memory to run. Having some CPU-bound processes and some I/O-bound processes in memory to- gether is a better idea than first loading and running all t...
clipped_os_Page_155_Chunk6372
156 PROCESSES AND THREADS CHAP. 2 On the other hand, when a user clicks on the icon that breaks the connection to the cloud server after the video has been uploaded, he has different expectations. If it has not completed after 30 sec, the user will probably be swearing a blue streak, and after 60 sec he will be foaming...
clipped_os_Page_156_Chunk6373
SEC. 2.4 SCHEDULING 157 The great strength of this algorithm is that it is easy to understand and equally easy to program. It is also fair in the same sense that allocating scarce concert tickets or brand-new iPhones to people who are willing to stand on line starting at 2 A.M. is fair. With this algorithm, a single li...
clipped_os_Page_157_Chunk6374
158 PROCESSES AND THREADS CHAP. 2 jobs, with execution times of a, b, c, and d, respectively. The first job finishes at time a, the second at time a + b, and so on. The mean turnaround time is (4a + 3b + 2c + d)/4. It is clear that a contributes more to the average than the other times, so it should be the shortest job...
clipped_os_Page_158_Chunk6375
SEC. 2.4 SCHEDULING 159 (a) Current process Next process B F D G A (b) Current process F D G A B Figure 2-42. Round-robin scheduling. (a) The list of runnable processes. (b) The list of runnable processes after B uses up its quantum. various tables and lists, flushing and reloading the memory cache, and so on. Sup- pos...
clipped_os_Page_159_Chunk6376
160 PROCESSES AND THREADS CHAP. 2 pecking order may be the president first, the faculty deans next, then professors, secretaries, janitors, and finally students. The need to take external factors into ac- count leads to priority scheduling. The basic idea is straightforward: each proc- ess is assigned a priority, and t...
clipped_os_Page_160_Chunk6377
SEC. 2.4 SCHEDULING 161 Priority 4 Priority 3 Priority 2 Priority 1 Queue headers Runnable processes (Highest priority) (Lowest priority) Figure 2-43. A scheduling algorithm with four priority classes. Multiple Queues One of the earliest priority schedulers was in CTSS, the M.I.T. Compatible TimeSharing System that ran...
clipped_os_Page_161_Chunk6378
162 PROCESSES AND THREADS CHAP. 2 Shortest Process Next Because shortest job first always produces the minimum average response time for batch systems, it would be nice if it could be used for interactive processes as well. To a certain extent, it can be. Interactive processes generally follow the pat- tern of wait for...
clipped_os_Page_162_Chunk6379
SEC. 2.4 SCHEDULING 163 Lottery Scheduling While making promises to the users and then living up to them is a fine idea, it is difficult to implement. However, another algorithm can be used to give similarly predictable results with a much simpler implementation. It is called lottery scheduling (Waldspurger and Weihl, ...
clipped_os_Page_163_Chunk6380
164 PROCESSES AND THREADS CHAP. 2 the CPU and the scheduler picks processes in such a way as to enforce it. Thus if two users have each been promised 50% of the CPU, they will each get that, no matter how many processes they hav e in existence. As an example, consider a system with two users, each of which has been pro...
clipped_os_Page_164_Chunk6381
SEC. 2.4 SCHEDULING 165 m i=1Σ Ci Pi ≤1 A real-time system that meets this criterion is said to be schedulable. This means it can actually be implemented. A process that fails to meet this test cannot be scheduled because the total amount of CPU time the processes want collectively is more than the CPU can deliver. As ...
clipped_os_Page_165_Chunk6382
166 PROCESSES AND THREADS CHAP. 2 2.4.6 Thread Scheduling When several processes each have multiple threads, we have two lev els of par- allelism present: processes and threads. Scheduling in such systems differs sub- stantially depending on whether user-level threads or kernel-level threads (or both) are supported. Le...
clipped_os_Page_166_Chunk6383
SEC. 2.4 SCHEDULING 167 Now consider the situation with kernel-level threads. Here the kernel picks a particular thread to run. It does not have to take into account which process the thread belongs to, but it can if it wants to. The thread is given a quantum and is for- cibly suspended if it exceeds the quantum. With ...
clipped_os_Page_167_Chunk6384
168 PROCESSES AND THREADS CHAP. 2 primitive is by showing how elegantly it solves the dining philosophers problem. The problem can be stated quite simply as follows. Five philosophers are seated around a circular table. Each philosopher has a plate of spaghetti. The spaghetti is so slippery that a philosopher needs two...
clipped_os_Page_168_Chunk6385
SEC. 2.5 CLASSICAL IPC PROBLEMS 169 #define N 5 /* number of philosophers */ void philosopher(int i) /* i: philosopher number, from 0 to 4 */ { while (TRUE) { think( ); /* philosopher is thinking */ take fork(i); /* take left for k */ take fork((i+1) % N); /* take right for k; % is modulo operator */ eat( ); /* yum-yum...
clipped_os_Page_169_Chunk6386
170 PROCESSES AND THREADS CHAP. 2 #define N 5 /* number of philosophers */ #define LEFT (i+N−1)%N /* number of i’s left neighbor */ #define RIGHT (i+1)%N /* number of i’s right neighbor */ #define THINKING 0 /* philosopher is thinking */ #define HUNGRY 1 /* philosopher is trying to get for ks */ #define EATING 2 /* phi...
clipped_os_Page_170_Chunk6387
SEC. 2.5 CLASSICAL IPC PROBLEMS 171 2.5.2 The Readers and Writers Problem The dining philosophers problem is useful for modeling processes that are competing for exclusive access to a limited number of resources, such as I/O de- vices. Another famous problem is the readers and writers problem (Courtois et al., 1971), w...
clipped_os_Page_171_Chunk6388
172 PROCESSES AND THREADS CHAP. 2 leave, they decrement the counter, and the last to leave does an up on the sema- phore, allowing a blocked writer, if there is one, to get in. The solution presented here implicitly contains a subtle decision worth noting. Suppose that while a reader is using the database, another read...
clipped_os_Page_172_Chunk6389
SEC. 2.6 RESEARCH ON PROCESSES AND THREADS 173 Similarly, much research in the operating systems community these days fo- cuses on security issues. Numerous incidents have demonstrated that users need better protection from attackers (and, occasionally, from themselves). One ap- proach is to track and restrict carefull...
clipped_os_Page_173_Chunk6390
174 PROCESSES AND THREADS CHAP. 2 PROBLEMS 1. In Fig. 2-2, three process states are shown. In theory, with three states, there could be six transitions, two out of each state. However, only four transitions are shown. Are there any circumstances in which either or both of the missing transitions might occur? 2. Suppose...
clipped_os_Page_174_Chunk6391
CHAP. 2 PROBLEMS 175 14. In Fig. 2-12 the register set is listed as a per-thread rather than a per-process item. Why? After all, the machine has only one set of registers. 15. Why would a thread ever voluntarily give up the CPU by calling thread yield? After all, since there is no periodic clock interrupt, it may never...
clipped_os_Page_175_Chunk6392
176 PROCESSES AND THREADS CHAP. 2 28. When a computer is being developed, it is usually first simulated by a program that runs one instruction at a time. Even multiprocessors are simulated strictly sequentially like this. Is it possible for a race condition to occur when there are no simultaneous ev ents like this? 29....
clipped_os_Page_176_Chunk6393
CHAP. 2 PROBLEMS 177 37. Suppose that we have a message-passing system using mailboxes. When sending to a full mailbox or trying to receive from an empty one, a process does not block. Instead, it gets an error code back. The process responds to the error code by just trying again, over and over, until it succeeds. Doe...
clipped_os_Page_177_Chunk6394
178 PROCESSES AND THREADS CHAP. 2 (a) Round robin. (b) Priority scheduling. (c) First-come, first-served (run in order 10, 6, 2, 4, 8). (d) Shortest job first. For (a), assume that the system is multiprogrammed, and that each job gets its fair share of the CPU. For (b) through (d), assume that only one job at a time ru...
clipped_os_Page_178_Chunk6395
CHAP. 2 PROBLEMS 179 script in the background and one in the foreground, each accessing the same file. How long does it take before a race condition manifests itself? What is the critical region? Modify the script to prevent the race. (Hint: use ln file file.lock to lock the data file.) 58. Assume that you have an oper...
clipped_os_Page_179_Chunk6396
180 PROCESSES AND THREADS CHAP. 2 true if the number is a perfect number and false otherwise. The main program will read the numbers N and P from the command line. The main process will spawn a set of P threads. The numbers from 1 to N will be partitioned among these threads so that two threads do not work on the name ...
clipped_os_Page_180_Chunk6397
3 MEMORY MANAGEMENT Main memory (RAM) is an important resource that must be very carefully managed. While the average home computer nowadays has 10,000 times more memory than the IBM 7094, the largest computer in the world in the early 1960s, programs are getting bigger faster than memories. To paraphrase Parkinson’s L...
clipped_os_Page_181_Chunk6398
182 MEMORY MANAGEMENT CHAP. 3 In this chapter we will investigate several different memory management mod- els, ranging from very simple to highly sophisticated. Since managing the lowest level of cache memory is normally done by the hardware, the focus of this chapter will be on the programmer’s model of main memory a...
clipped_os_Page_182_Chunk6399
SEC. 3.1 NO MEMORY ABSTRACTION 183 (a) (b) (c) 0xFFF … 0 0 0 User program User program User program Operating system in RAM Operating system in RAM Operating system in ROM Device drivers in ROM Figure 3-1. Three simple ways of organizing memory with an operating system and one user process. Other possibilities also exi...
clipped_os_Page_183_Chunk6400