Scarica Operating System: Processes and Threads - Differences, Communication, and Implementation e più Appunti in PDF di Sistemi Operativi solo su Docsity!
Processes and Threads summary
DIFFERENCES BETWEEN A MULTIPROGRAMMING SYSTEM AND A MULTIPROCESSOR SYSTEM.
- Multiprogramming system : CPU works from a program to another
every tenths or hundreds of milliseconds
each one.
- Multiprocessor system : Provides 2 or more CPUs that use the same
physical memory. The “process and
threads” is a conceptual model which
allows humans to deal with parallelism in an
easier way.
SEQUENTIAL PROCESS MODEL The entirety of the executable software is divided into sequential processes. Process : is any running program. A process includes also: program values, registers values and variables. Conceptually is easier for us to think that each process have its own virtual CPU and imagine a collection of processes running in a semi parallel way rather than try to understand in which way the CPU is shared between processes. This picture represents a multiprogrammed computer with 4 programs in memory and only one program counter. This picture shows 4 different programs each one with its own flow control. There’s only a physical program counter and therefore every time that a process returns its execution its logical program counter must be loaded into the real program counter. When a process ends the time interval assigned to it, it has to be saved.
This picture shows us how each process has progressed over time. It clearly shows that in every single moment there’s only a process active. The speed with which the CPU executes each single process may vary even in the various executions of the same process. DIFFERENCES BETWEEN PROCESSES AND PROGRAMS Example : We have a computer scientist, who is also a lover of cooking, that want to prepare a birthday cake for his daughter. We consider the following elements:
- The recipe = program
- The computer scientist = processor/CPU
- the ingredients = input data
- The steps of the recipe and the execution of the same / adding the ingredients = the Process Imagine now that the computer scientist’ son enter the kitchen because stung by a bee. The scientist will stop making the cake to take care of him and when he’ll finish doing it he’ll resume cooking. This explain how the CPU stop executing a process to start the execution of another one and then resume working on the first one when he’s done with it. PROCESSES CREATION The operating systems must allow the necessary processes to exist. The followings are 4 events which might create a new process:
- System initialization
- The execution by a process of a system call to create a new process
- The user’s request to create a new process.
- The beginning of a batch work. When an operative system is started 2 different types of processes are created:
- Surface processes : which are the ones which interact with the user ù
- Background processes : which can be the program that accepts incoming email and that activates itself only when a new email arrives. Creates a process can be helpful when there’s a large amount of work that needs to split in more little works. We can consider the scenario of a huge quantity of data that need to be extracted from a network to be then executed.
PROCESS TERMINATION These are the most common causes leading to the termination of a process :
- The process completes its work and voluntarily terminates
- The process detects an error and voluntarily terminates.
- The system detects a fatal error in the process and forces its termination
- Another process forces the process termination. In Unix it can happen using a kill system call CASE 1 Most of the process terminates because they have completed their work and when it happens the compiler executes a system call, exit in Unix, to tell the OS that it is completed. CASE 2 When the process finds a fatal error it terminates. For example if the user want to compile the program foo.c and he types the command “cc foo.c” but the file does not exist the compile will simply terminate. Usually a pop-up dialog which asks for correct parameters is displayed instead of simply quitting the execution. CASE 3 This type of error is usually caused by a programming error as the execution of an illegal instruction, the reference to a non existent memory location or a division by 0. In Unix if the process receive a signal that interrupts it, it may tell the OS that it want to handle some errors itself instead of terminating abruptly. CASE 4 In this case the process terminates because another process executes a system call telling the OS to quit the process. In Unix this system call is “kill” PROCESS HIERARCHIES A process only have a parent but can have 0,1,2,3… child processes and this creates a hierarchy that is called “Process Group”. In Unix ’s processes groups if user enter a “cntr +c” key command it is transmitted to all the processes in the group which are associated with keyboard and each process can decide if to capture the signal, to ignore the signal or if to keep the default action and be killed by the signal. In unix there’s a process in the boot image called “init” and when it begins its execution it reads a file containing the numbers of terminals the system has. Then the init creates a new process per terminal through a fork system call. These processes wait for a user to connect to the system through the corresponding terminal and each time someone connects to a terminal the process associated to it will execute a shell to accept commands. => all processes belong to a hierarchy tree with the init process as root. In Unix parents processes cannot ignore their children.
STATES OF A PROCESS Each process is a separate entity and each has its own internal counter. Processes often need to interact with other processes and for example a process can generate output data that another process uses as input data. cat chapter1 chapter2 chapter3 | grep tree The first process, which is the one that executes the cat, produces the concatenation of the three files as output. The second process, which runs grep, selects all the line that contains the word “tree”. Depending on the relative speed of the two processes it may happen that grep is ready to run but there is no input waiting to be processed by it and in this case the process that run grep should be blocked until some input is available. When a process hangs it does it for 2 different situations:
- Because it cannot continue, usually because it is waiting for some input data that is still not available
- or because the OS has temporarily decided to allocate the CPU to another process. These situations are completely different because in the first one the suspension is inherent to the situation while the second one is a technical system issue. RUNNING BLOCKED READY
Transitions:
- The process hangs waiting for data
- The scheduler selects another process
- The planner selects this process
- The data is available A process can be in 3 states :
- Running (actually using the CPU at the time)
- Ready (executable, temporarily stopped to allow another process to run)
- Blocked (unable to run until some external event occurs)
PROCESS IMPLEMENTATION To implement the process model the OS maintains the process table which contains an input per process. Each of these entries can be called both descriptor or process control block and they contain information on :
- the status of each process
- its program counter
- its stack pointer
- its memory allocation
- the status of its open files
- information related to its planning
- the accounting of the resources it had consumed
- Any information about the process that must be saved when the process switch from running state to ready or blocked state so that its execution can be resumed later as if it never stopped. How is it possible to offer the illusion of the existence of multiple sequential processes execution on a single CPU machine and many I/O devices? Each class of I/O devices, such as floppy drives ,hard drives or terminals, is associated with a memory location called VECTOR OF MEMORY The vector of memory contains the address of the interrupt handling routine that serves these types of devices. Eg: if process number 3 is interrupted by the hard disk at the moment of the interruption the program counter of user process number 3, the program status and some other register are stored and when the CPU wants to resume the process it jumps to the address specified in the vector of memory. Every interruption starts with saving the records, the information previously stacked by the hardware is unstacked and the pointer is set to a temporary stack used by the controller process. All of these action cannot be expressed by an high level language so they are performed by a small assembly language routine, which is usually the same for all the interrupted processes.
PROCESS TABLE:
1st COLUMN : fields related to the management of the processes 2nd COLUMN : memory management 3rd COLUMN : file management
When the routine is over, it makes a call to a C procedure (if we assume that the OS is written in C). When all this procedures are over the scheduler is ready to determine which ready process runs next. THREADS In traditional OS each process has its own address space and a single thread of control. There are some situations where it’s utile to have multiple threads in the same address space running quasi-parallel as if they were separate processes. THE THREADS MODEL
- 1st way of looking at a process : As a way of grouping related resources together, the process has an address space containing program code and data as well as other resources as for example open files, child processes etc. By putting all these resources together in the form of a process they can be handled in an easier way.
- 2nd way of looking at a process : The process includes an execution thread. The thread contains a program counter which instruction to execute next. It contains a stack which is a sort of history of its execution with a frame for each procedure that has been called but not yet returned. The concept of process and the one of thread are different and can be treated separately. PROCESSES: used to group resources together THREADS : entities scheduled to run on the CPU Thread are an addition on the processes model because they allow multiple execution in the same environment determined by a process and they have an high independence from those executions.
SUMMARY
- The hardware stacks the program counter
- The hardware load the new program counter from the interrupt vector
- An assembly language routine saves the records
- An assembly language routine establishes a new battery
- The written interruption handling routine is executed in C (normally read and buffer the data from entry)
- The planner decides which process to run next
- A procedure written in C returns to the code in assembler
- An assembly language routine passes to execution of the process selected by the planner
Threads can be in any of the following states : Running, Ready, Blocked As for the processes :
- a Running Thread currently has the CPU and is active
- a Blocked Thread is waiting for some event to unblock it
- a Ready Thread is scheduled to run and it does as soon as its turn comes. States transitions are the same of processes. As shown in the table above each thread has a stack which contains a frame for each procedure that has been called but not yet returned. This frame contains the local variables of the procedure and the return address to use when the procedure call ends. ATTRIBUTES OF PROCESSES ATTRIBUTES OF THREADS Address space Program counter register Global variables Stack Open files State Child processes Pending alarms Signals and signal drivers Accounting informations Pila = Stack
THREAD_CREATE
In a multithread system the processes usually starts with a single thread which has the ability to create other threads by calling a library procedure as “thread_create”. One of the parameters “thread_create” has is the name of the procedure that the thread will execute. Usually there is no hierarchical relationship between threads but it can happen that they maintain a parent-child relationship. THREAD_EXIT The library “thread_exit” is called a thread finishes its work and want to end its life. When the thread exit is call the thread vanishes. THREAD_WAIT In some thread systems this call allows to a thread to wait for another thread to finish and this blocks the invoking process until a specific thread terminates. THREAD_YIELD This call allows a thread to voluntarily leave the CPU to permit some other thread to execute. This call is important because it does not exist in the case of processes. THREADS PROBLEMS
- Threads are really useful but they introduce some complications to the programming model. For example in Unix OS they affect the behavior of the FORK call. For example if the parent process has a certain number of threads must the child process have them as well? If not the process might not work properly however if it has the same number of threads as the parent another problem could show up:
- What happen if a parent thread hangs on a call to read from the keyboard? Does this block one thread of the parent and one of the child process? Or only one of them?
- Another problem is given by the fact that thread share a huge number of data structure, what happen if a thread closes a file while another thread is reading it? These problems can be solved with some effort but this requires a careful analysis and design in order make the multithreaded programs work in good way. USE OF THREADS One of the reasons why it is convenient to use threads is that there are many applications in which many activities are performed simultaneously and, in some moments some may crash and in this case it is easier to break the application into several sequential threads that are executed in parallel and the reason is the same as the processes. With threads we introduce the concept of the ability of parallel entities of parallel entities to share an address space and all its data among themselves and it is fundamental for some applications.
Threads can also be useful in the case of a WWW (world wide web) server The server receives requests for pages and then sends them to the clients Some web pages may be more requested than others and this is exploited by web servers to improve their performance by creating the "cache" which can be considered a collection of all frequently used pages. the cache allows you to access pages without having to access the disk to get them. The model described above allows the server to be written as a collection of sequential threads. The dispatcher is formed by an infinite loop: it receives a work request and manages it with the worker threads. The worker thread checks if the page is present in the cache: If yes, the page is sent to the client and the thread is blocked waiting for a new request. If it is not in the cache, the page is searched on the disk and sent back to the client and the worker thread is blocked waiting for a new request. The following code represents what described above: This image shows one way to organize the web server. The Dispacher thread reads the service requests made to it through the network. Then it choose an idle worker thread and passes the request to it and then block it. The dispatcher unlocks the worker thread which goes to the ready state.When the worker thread goes into execution it checks if the cache can satisfy the request of the web page (to which all threads have access). If not, the thread reads the disk to obtain the page and it enter the blocked state until the operation is complete. Now antoher worker threaaad in ready state, or the dispatcher, will be execute. This is about the dispatcher This is about the worker thread
How the server should have been written in absence of threads:
- Server operate as a single thread : The main web server loop takes a request and serves it until it is completed and then move to the next request. So the server will be idle while waiting for the disk read and in the meantime it will not be able to process any other request.
- The Web server is running into a dedicate machine and the CPU is idle while the web server I waiting for the disk. The result is that the “net” is able to read fewer pages then using threads
- A third approach to the problem is : when a new request comes in it is examined by the only existing thread. If it cannot be find in the cache a non-blocking disk read operation. Is started. The server saves the status of the request in a table and it goes on the next event. The event can be another request or a response of the disk to a previous read operation. If it is the second one the main information is extracted form the table and the response is processed. The response in this case will be in the form of a signal or interrupt. This can be considered as a system which has a non-blocking version of the read system call. In the 3rd model the status of request must be explicitly saved in the table and it has to be restored each time the server switches from working on one request to another and this a more complicate way to simulating threads and their stacks. Threads are useful because they offer us the idea of sequential processes, which make blocking system call, without loosing parallelism. Blocking system calls make programming easier and parallelism improves performances. The third model has high performances but it is difficult to program because of the use of non-blocking calls. Summary: Threads are also useful in applications that must process a huge amount of data. The common approach is :
- Read a block of data
- Process it
- Write it again The problem is if only the blocking system calls are available the process will hang while the data is coming in and the results are being written and it cause the CPU to be blocked and having the CPU idle while there’s a lot of work to do is a waste of time and resources that Model Characteristics Threads Parallelism and blocking system calls Single-wire process No parallelism and blocking system calls Deterministic finite automation Parallelism, non-blocking system calls and interrupts
When threads are managed in user space each process needs its own private thread table to keep track of its threads. This table also exists in the kernel mode. The table controls program counter of threads, its stack pointer, its registers, its status and the table is managed by the system at the run time. When a thread goes to the blocked or ready state the information necessary to continue the execution later is saved into the thread table. There’s a procedure that, when a thread does something that can cause its block, controls if it should switch in the blocked status and in case its records are saved into the thread table. Then the procedure looks for a thread in the ready status and reload the machine with the values of this new thread. When the pointer of the stack and the pointer of the program switch their value the thread comes back to life again. If the machine has an instruction to save all the registers and on to load all of them then switching from a thread to another can be done by executing some instructions. The procedures to save the status of thread and the scheduler are local procedures so their invocation is more efficient than making a call to the kernel. Example :
- A thread finishes its execution by calling a thread_yield
- The thread_yield saves the thread’s information into the thread table
- The scheduler can choose another thread to run Planning thread is very fast because there’s no need of switch context or empty the cache etc.. Another benefits of thread is that they are good for beginners because they allow each process to have its own planning algorithm adapted to its need. For some applications, as for example the ones with a Garbage collector, it doesn’t matter if a thread stops at the wrong time. Threads requires some space for the thread table and this can be a disadvantage when a huge number of thread is required. Even if using threads at the user-level has an high efficiency it also has a lot of problems, as for example:
- the way blocking system-calls are implemented :
- Suppose that a thread has read from the keyboard before any key have been pressed
- The thread can make a system call which will block all the threads in process and this is unacceptable A way to solve this problem is to modify all system calls so that they are not blocking for example by making the read call on the keyboard immediately return 0 if there are no characters in the keyboard buffer. Require changes at the OS is not a good idea because :
- Threads implementation at the user level has been thought of to be executed on existing OS
- The required changes require also changes to part of the already existing user programs
A second alternative is possible in case it can be determined in advance whether a system call will be blocked. In the Unix OS there is a "select" call that allows the user to know if a specific read call he wants to make will be blocked. If this call is available and the selection call has not yet been made, then this will be replaced by a new call that will be made. If, on the other hand, the read call is about to cause a block, the call is not made and another thread is executed. This approach requires the rewriting of some parts of the system call library and is inefficient, but there is no other choice. The code that was added into the system call is called a jacket or wrapper. A problem similar to that of the system call block is what occurs when a program jumps to an instruction that is not present in that memory. (Computers are configured not to have an entire program in main memory). In this case a “Page fault” occurs and the OS has to fetch the missing instructions from the disk. The process waits until the necessary instructions have been located and read. When a page fault occurs the kernel, which is not aware of the existence of the thread, blocks the entire process until the I / O is complete. Another problem with threads is that if one of them runs, the others won't be able to do so until the CPU is voluntarily given to them. There is the possibility of programming the execution of threads according to the "Round Robin" algorithm which allows you to have execution shifts. The scheduler never has the ability to pass another thread to execution. A possible solution to the problem of the indefinitely long execution of threads is to use a clock/interrupt signal that takes control every second for example during execution. However, clock interruptions are not always available at high frequencies and can create overloads on the system. In addition, a thread may need its own clock which could interfere with the use of the system clock. The most important problem regarding threads is the fact that programmers want to use threads in the applications in which threads are often blocked. An example is a multi thread web server. Those threads always make system calls and once the thread has forced the kernel to make a system call it does not mean so much more work for the kernel to switch to another thread if the first one hangs and this can eliminate the constant need of to calls to the select system to check if the read system calls are safe.
HYBRID IMPLEMENTATION In the picture above the kernel is aware only of the kernel-level thread and only takes care of their scheduling. Some of this threads might have multiple user-level threads multiplexed on them and these user level threads are created, destroyed and scheduled as the user-level threads running Ina non multithreaded system. In this way kernel level threads have some set of user level thread. SCHEDULER ACTIVATIONS This is one of the ways researchers have tried to combine the advantages of user-level implementation with the advantages of kernel-level implementation. This approach was designed by Anderson in 1992 and he worked on the triggers of the scheduler and the goals of his research was to combine the functionality of kernel-level threads with the higher performances and flexibility associated with thread packages at the user-level. In a more specific way he wanted the user-level thread not to make non-blocking system calls or check in advance whether if it’s safe or not to make certain system calls. But when a thread is blocked in a system call due to a page fault, it must be possible to execute other threads within the same process. The efficiency in this model is achieve by avoiding unnecessary transitions between user space and kernel space/ core. Example : if a thread is waiting for another one to do something, there is no need to involve the kernel. When scheduler triggers are used the kernel allocates a certain number of virtual processor to each process and lets the system to allocate threads to processors at run time. This model can be used also on multiprocessors system where virtual processors can be CPUs. The number of virtual processors assigned to a process is initially 1 but it can be increased if the process needs more. The kernel can reallocate processors to processes that are more in need. The main idea is :
- The kernel detects that a thread has hung for any reason
- The kernel notifies the system at execution time of the process by passing it as parameters on the stack the number of the thread in question and a description of the event that occurred. This kind of implementation want to combine both user-level and kernel implementation. In a more specific way the purpose, as shown in the image, is to use kernel- level threads and multiplex user-level thread onto some or all of the kernel- level thread.
- An UPCALL took place by notifying, in the form of activation by the system kernel at runtime to a known start address
- Once activated the runtime system can reschedule its threads by marking the current thread as blocked
- Then it takes another thread from the ready threads list
- Later when the kernel detects that the original thread can be executed again the kernel makes another upcall to the system at runtime to report this.
- The runtime system can decide at that moment whether to immediately restart the blocked thread or to put it in the ready threads list to be executed later. When a Hardware interruption occurs the CPU goes into Kernel mode. The interruption can be of 2 types
- It can not be linked with the interrupted process and in this case the interrupted thread will later be put into the same state it was before the interruption
- It can be linked to the interrupted process and in this case the thread will not be restarted and will be put in suspended status and the virtual CPU will decide which thread to schedule on the CPU between the interrupted thread, the newly prepared one or a third chosen thread One problem of scheduler triggers is that it violates the structure of any layered system : Layer n offers certain services that Layer n+1 can invoke but Layer n cannot invoke procedures that are in Layer n+ EMERGING THREADS OR POP-UP THREADS Threads are useful on distributed systems. How they handle messages in the traditional way :
- When a message arrive the process or thread accepts it and processes it An alternative way is :
- When a message arrives the system creates a new thread, called pop-up thread, to handle the message When using pop-up threads things have to be planned in advance. For example the process in which the thread is running have to be taken into account. Usually making the pop-up threads int he kernel mode it’s easier but if it is buggy it can cause a lot of damage. Creation of a new thread a) before the message arrives b) After the message arrived