Operating System Principles Chapter II process management (2)

2.4 classic synchronization process

2.4.2 Dining Philosophers

1. The use of the recording semaphore solve Dining Philosophers
After analysis, the chopsticks on the table is a critical resource, at a time only allows the use of a philosopher. In order to realize exclusive use of the chopsticks, chopsticks may represent a semaphore, the semaphore array constituted by these five semaphore. It is described as follows:

Var chopstick: array[0, …, 4] of semaphore;
所有信号量均被初始化为1, 第i位哲学家的活动可描述为:     
      repeat
   	 wait(chopstick[i]);
    	wait(chopstick[(i+1) mod 5]);
      		…
   	 eat;
                             …
   	 signal(chopstick[i]);
   	 signal(chopstick[(i+1) mod 5]);
     	            …
   	 think;
  until false; 

May take the following solutions:
(1) at most four philosophers have only allowed to pick up chopsticks while on the left, eventually ensure that at least one philosopher can eat, and when you finish using it can release he spent two only chopsticks, so that more philosophers can eat.
(2) only when the philosopher left and right two chopsticks are available, allowed him to pick up chopsticks meal.
(3) a predetermined odd number of chopsticks philosopher acquire his left and right chopstick get another; and the even-numbered philosopher opposite. This provision, would be 1, No. 1 No. 2 philosophers competition chopsticks; 3,4 philosopher chopsticks 3 competition. That first competition in five philosophers odd number of chopsticks, after obtaining, go to the competition even-numbered chopsticks, and finally there will always be a philosopher to get two chopsticks and eat.
AND 2. Use
the dining philosophers problem, it is required to obtain the two philosophers each critical resource (chopsticks) in order after a meal, which is AND synchronization described earlier, it is available with an AND signal mechanism in nature the most simple solution.

Var chopsiick array [0, …, 4] of semaphore∶ =(1,1,1,1,1);
processi
repeat
think;
Sswait(chopstick[(i+1) mod 5], chopstick [i]);
eat;
Ssignat(chopstick [(i+1) mod 5], chopstick [i]);
until false;

2.4.3 Readers - writers problem

1. The use of the recording semaphore solve readers - write the problem
to realize mutual exclusion between the Reader and Writer process when reading or writing and set up a mutex Wmutex. In addition, and then set an integer variable representing the number of Readcount was reading process. Because as long as there is a Reader in the process of reading, they are not allowed to write Writer process. Therefore, only when Readcount = 0, represents no progress in reading Reader, Reader process only needs to perform Wait (Wmutex) operation. If the wait (Wmutex) operation is successful, Reader can read process, accordingly, do Readcount + 1 operation. Similarly, only when the Reader process after performing Readcount decremented its value is 0, it will be required to perform signal (Wmutex) operation, so that the process of writing Writer. And because Readcount is a critical resource that can be accessed more Reader process, therefore, we should set a mutex rmutex for it.

Readers - writers problem can be described as follows:

Var rmutex, wmutex:semaphore∶   =1,1;
    Readcount:integer∶   =0;
    begin
    parbegin
     Reader:begin
        repeat
         wait(rmutex);
         if readcount=0 then wait(wmutex);
          Readcount∶   =Readcount+1;
         signal(rmutex);
           …
         perform read operation;
           …
wait(rmutex);
         readcount∶   =readcount-1;
         if readcount=0 then signal(wmutex);
         signal(rmutex);
        until false;
       end
    writer:begin
        repeat
         wait(wmutex);
         perform write operation;
         signal(wmutex);
        until false;
       end
    parend
  end

2. Use semaphore set mechanism to address the reader - to write the problem

Var RN integer;
L, mx:semaphore∶ =RN,1;
begin
parbegin
reader:begin
repeat
Swait(L,1,1);
Swait(mx,1,0);

perform read operation;

Ssignal(L,1);
until false;
end
writer:begin
repeat
Swait(mx,1,1; L,RN,0);
perform write operation;
Ssignal(mx,1);
until false;
end
parend
end

2.6 Process Communication

2.6.1 Types of Process Communication

1. The shared memory system

  • Communication mode based on shared data structures
  • Communication mode based on the shared storage area

2. messaging system
, whether a stand-alone system, multi-machine system, or computer network, message passing mechanism are among the most widely used process communication mechanism. In the messaging system, the data exchange between processes is formatted message (message) units; in a computer network, referred to as a message packet again. Programmer communicates directly with a set of system-provided communication command (primitives). Operating system hides the implementation details of communication, greatly simplified the complexity of communication programming, and access to a wide range of applications. Communication system is an advanced messaging communication. Because of its different implementations is further divided into a direct communication and indirect communication ways.

3. conduit (Pipe) communication
so-called "pipeline" means for connecting a reading process and a writing process in order to achieve a shared file communication between them, also known as pipe file. Provides input to pipeline transmission process (shared files) (i.e. writing process), the character stream to form a large amount of data into the pipe; received process accepts the output of the pipe (i.e. the reading process), from the pipe receiving (reading) data. Since the transmitting and receiving processes is the use of pipes for communication, it is also known a communication pipe. In this manner first in UNIX systems, because it can efficiently transfer large amounts of data, which is also incorporated into many other operating systems.

In order to coordinate communication between the two sides, the pipeline must provide a mechanism for coordination of the following three areas:

  1. Mutually exclusive, that is, when a process is executing reading of the pipe / write operations, other processes have to wait.
  2. Synchronization means that when the writing process a certain amount of data written to pipe, then go to sleep to wait, knowing that after the removal of the data read process, and then wake him. When the reading process reads an empty pipe, sleep should wait until after the write process to write data to the pipe, it will only wake.
  3. When determining whether or not there is the other side, only to determine the other already exists, to communicate.

2.6.2 Implementation messaging communication

1. Direct communication
which transmitting means transmits a command using the process provided by the OS, to send the message to the target process. At this time, transmitting and receiving processes required are explicitly provided to the other identifiers. Typically, the system provides the following two communication command (primitive):
the Send (Receiver, Message); send a message to the receiver process;
the Receive (Sender, Message); receiving a message sent by the Sender;
e.g., primitive Send (P2 , m1) shows a process of sending a message to the receiving m1 P2; the primitive Receive (P1, m1) is represented by the received message sent m1 P1.

In some cases, the receiving process may be in communication with a plurality of the sending process, and therefore, it can not be specified in advance sending process. For example, a process for providing printing services, it may receive a "print request" message from any one process. For such applications, the process of the source primitive parameters message received in the reception process is a value after completion of the communication, receiving primitive may be expressed as:
the Receive (ID, Message);

We can also take advantage of direct communication primitives to solve the producer - consumer issues. When the producers to produce a product (the message), then sends the message to the consumer with a Send primitive processes; and consumers use Receive process is primitive to get a message. If the message has not been produced, consumers must wait until the producer process sends a message over. Producer - consumer communication process can be described are as follows:

repeat
      …
    produce an item in nextp;
      …
    send(consumer, nextp);
   until false;
   repeat
    receive(producer, nextc);
      …
    consume the item in nextc;
  until false; 

2. Indirect communication system
(1) creation and destruction of the mailbox.
The process can be used to create mail primitive to create a new mailbox. Creator process should be given mailbox name, mailbox attributes (public, private or shared); for a shared mailbox, the name should be given sharers. When a process no longer need to read the mail, mail can be used to undo the undo primitive.
(2) sending and receiving messages.
When you want to use for communication between processes mailbox, the mailbox must be shared, and by the following communication primitives provided by the communication system.
Send (mailbox, message); a message to the specified mailbox;
the Receive (Mailbox, Message); receiving a message from the specified mailbox;

Mail created by the operating system, also created by the user process, the creator is the owner of the mailbox. Accordingly, the mailbox can be divided into the following three categories.

  • Private mail
    can create a new mailbox for the user own process, and as part of that process. Mailbox owners can read messages from the mailbox, other users can only send messages to their own constitute the mailbox. Private mail may be employed such a unidirectional communication link mailbox achieved. At the end of the process that owns the mailbox, the mailbox will disappear.
  • Public mailbox
    which consists of creating an operating system and made available to the system all use approval process . The approval process can send a message to the mailbox, it can be read from the message sent to his mailbox. Obviously, the common mailbox should be two-way communication link is achieved mailbox. In general, the public mailbox is always present during system operation.
  • Sharing mailbox
    after it was created by a process when creating or created, indicating it is shared, and must indicate the name of a shared process (user). Mailbox owners and sharers, have the right to take away from the mailbox to send your own message.

When using mailbox communications between the transmitting and receiving processes, the following four relationships:

1.一对一关系。这是可为发送进程和接收进程建立一条两者专用的通信链路,使两者之间的交互不受其他进程的干扰。
2.多对一关系。允许提供服务的进程与多个用户进程之间进行交互,也称为客户/服务器交互。
3.一对多关系。允许一个发送进程与多个接收进程进行交互,使发送进程可用广播方式,向接受者(多个)发送消息。
4.多对多关系。允许建立一个公用信箱,让多个进程都能向信箱中投递消息;也可从信箱中取走属于自己的信息。

2.6.3 Problems messaging system implementations

1. The communication link
to enable communication between the transmitting and receiving processes, must establish a communication link therebetween. There are two ways to establish a communication link. The first way is: the sending process before the communication, with explicit "Establish Connection" command (primitives) to whom the request to establish a communication link system; the link after use, also explicitly removal by chain road.
This approach is mainly used in computer networks. The second way is to send a clear process without requesting the establishment of a link, send commands provided by the system (primitive) use only, to whom the system will automatically establish a link. This approach is mainly used in stand-alone systems.
The method of connection of a communication link, the communication link in turn divided into two categories: ① point - point connection communication link , then only a link connecting the two nodes (processes); ② multipoint connection link It refers to a link connection with a plurality of (n> 2) nodes (processes). According to a different communication scheme, the link can be divided into the two ways: ① a unidirectional communication link , only the sending process to send a message to the receiving process; ② bidirectional link , send a message to either allow the process B by the process A, also allows a process send a message to process B A.

Format of the message
in some OS, the message is the use of relatively short fixed-length message format, which reduces the processing and storage overhead message. This approach can be used in office automation systems, provide fast scratch pad for the user communications; but longer message to be transmitted to the user is inconvenient. In some OS, the use of another variable length message format, i.e., the length of the message is sent the process variable. When the system becomes long message processing and storage, you have to pay more overhead, but facilitate the users. Both message formats have advantages and disadvantages, so in many systems (including a computer network), are simultaneously used.

3. Process Synchronization mode

  1. Sending process blocked, blocked the receiving process.
  2. Sending process is not blocked, blocked the receiving process.
  3. Sending and receiving processes are not blocked.

2.6.4 Message buffer queue communication mechanism

1. The message buffer queue data structure of communication mechanisms

  1. Message buffer. In the communication message buffer queue, the primary use of the data structure is a message buffer.
  2. PCB data items relating to communication. When using the message buffer queue communication mechanism is provided at the same time the message buffer queue, should be added to the message queue for the semaphore operation and to achieve synchronization, and places them in the PCB process.

2. sending primitive
sending process before sending the message sending primitive use, should be in its own memory space, provided with a transmission region a, as shown in Figure, the body of the message to be transmitted, the transmission process identifier, message length, etc. information fill it, and then call the send primitive, to send the message to the target (receiving) process. First, according to the message sending primitive a.size length of a transmission region set in the buffer to apply a i, then a copy of the information transmitted to the buffer area in i. In order to be able to hang inside the message queue i mq receiving process, the process should obtain received identifier j, then i hung on j.mq. Since the critical resource belongs to the queue, it is executed before and after the insert operation must wait and signal operations performed.
Communication message buffer

procedure send(receiver, a)
     begin
        getbuf(a.size,i);                         根据a.size申请缓冲区;
        i.sender∶   =a.sender;  将发送区a中的信息复制到消息缓冲区之中;
        i.size∶   =a.size;
        i.text∶   =a.text;
        i.next∶   =0;
       getid(PCB set, receiver.j);   获得接收进程内部标识符;
       wait(j.mutex);
       insert(j.mq, i);   将消息缓冲区插入消息队列;
       signal(j.mutex);
       signal(j.sm);
    end 

3. Receive primitive


接收原语描述如下:
procedure receive(b)
   begin
    j∶   =internal name; j为接收进程内部的标识符;
    wait(j.sm);
    wait(j.mutex);
    remove(j.mq, i); 将消息队列中第一个消息移出;
    signal(j.mutex);
    b.sender∶   =i.sender; 将消息缓冲区i中的信息复制到接收区b;
    b.size∶   =i.size;
    b.text∶   =i.text;
  end

2.7 thread

2.7.1 The basic concept of threads

1. Process operations
to make the program can execute concurrently, the system must also be about a series of operations.

  • Create a process
  • Revocation process
  • Process switch

2. Thread the property

  • Light entity
  • The basic unit of scheduling and dispatching of independence
  • Can be executed concurrently
  • Resource sharing process

3. The state of the thread
(1) status parameter.
Each thread in the OS can be described using a thread identifier and a set of status parameters. There is often several state parameters: ① register state, including the contents of the program counter PC and stack pointers; ② the stack, the stack is usually stored in the local variables and return addresses; ③ threads running state, the thread is used to describe in what operating state; ④ priority, the priority level of a thread of execution described; ⑤ thread-specific memory for storing its own local variable copy thread; ⑥ signal shielding, i.e. be shielded for some signals.

(2) threads running.
As with the traditional process, as between the threads there are constraints shared resources and mutual cooperation relations, resulting threads also have intermittent at runtime. Accordingly, when the thread runs, also having the following three basic states: ① execution state, the processor represents a thread is obtained operate; ② the ready state, the thread means has performed with a variety of conditions, can be performed once CPU state; ③ blocking state, refers to the thread is an event hampered in execution, in a state of suspended.

4. creation and termination of threads
in a multithreaded OS environments, applications at startup, usually only one execution thread, the thread is known as the "initialize the thread." It may need to go to create a number of threads. When creating a new thread, need to use the function to create a thread (or system call), and provide the appropriate parameters, such as the entry point to the main thread pointer, the size of the stack, and the priority for scheduling the like. Create a function in a thread executed, returns a thread identifier for later use.
Terminate the thread in two ways: one is the thread to complete the voluntary exit after their work; the other is the wrong thread for some reason or appear to be forced to terminate other threads in the operation.

5. Multi-threaded OS operating in
a multi-threaded OS, the process is used as the basic unit of the system has the resources, the usual process contains multiple threads and provide resources for them, but this time as a process is no longer performed entity. Multi-threaded OS in the process has the following properties:

  • As a unit of allocation of system resources
  • May include multiple threads
  • Process is not an executable entity

2.7.2 Synchronization and communication between threads

1. mutex (mutex)
mutex is a relatively simple mechanism for implementing the inter-process exclusive access to resources. Since the operation time and space are low mutex lock, and therefore more suitable for high frequency data using the key and shared block. Mutex can have two states, i.e., unlocking (UNLOCK) and the off-lock (lock) state. Accordingly, the available two commands (functions) of the mutex operations. Wherein the lock is operable to shut off the mutex, the unlocking operation for opening the unlock mutex.

2. The condition variable
for each condition variable is usually used in conjunction with a mutex, that is, when you create a mutex will be linked with a condition variable. Simple mutex lock for the short-term, mainly used to ensure mutual exclusion to enter the critical section. The condition variable is used for the long-awaited thread waits until resources become available.
First thread execution mutex lock off operation, if successful, will enter the critical section, and then look for the data structures used to describe the state of the resource, in order to understand the situation of resources. If we find the desired resource is in a busy state R, the thread into the wait state, and performs the unlock operation mutex wait for the resource to be released; if the resource is in an idle state, indicates that thread can use the resource, then the resource setting busy state, then performing unlocking operation on the mutex.

Here Insert Picture Description
3. semaphore mechanism

  1. Private semaphore
    When a thread needs to achieve synchronization between threads in the same process using the semaphore, can call creates a semaphore command to create a private semaphore, its data structure is stored in the address space of the application in. Private semaphore belonging to a specific process for all, OS does not know the existence of private semaphore, therefore, once occupied by the private semaphore normal occurrence of abnormal termination or end, but did not release the semaphore occupied space case , the system will not be able to restore it to 0 (empty), nor can it convey it to the next thread request.
  2. Public Semaphore
    public Semaphore is a different process to set synchronization among threads of different processes to achieve sometimes. Because it has a public name for all processes use, and therefore called it a common semaphore. Data structure stored in the system memory area is protected in the space allocated for it and managed by the OS, it is also known semaphore system. If the semaphore occupants at the end of the common semaphore is not released, the OS will automatically signal the recovery of the amount of space, and notify the next process. Visible, public semaphore is a relatively safe synchronization mechanism.

2.7.3 kernel support for threads and user-level threads

1. Kernel support thread
here so-called kernel support for threads, also is running with the support of the same kernel, that both user threads in the process, or system threads in the process, their creation, undo and handover, also relying on the kernel implementation. Further, also in the kernel space kernel support each thread is provided with a thread control block, the kernel is based on the control block and to sense the presence of a thread, and for its control.
2. User-level threads
user-level threads exists only in user space. For the creation of this thread, undo, synchronization and communication between threads and other functions, all without the use of system calls to achieve. For switching user-level threads, usually occurs between the many threads of an application process, then, also need kernel support. Due to the simple rules than the process of scheduling and switching rule for switching, so the switching speed of the thread is particularly fast. Seen, this thread is related to the kernel.

2.7.4 Thread Control

1. implement kernel support for threads
Here Insert Picture Description
2. To achieve user-level threads

  1. Runtime (Runtime System) When
    the so-called "runtime system", is essentially a collection of threads to manage and control the function (procedure), which includes functions for the creation and destruction of threads, thread synchronization and communication functions and the realization of thread scheduling function and so on. Because of these functions, in order to make user-level threads related to the kernel. All runtime system functions reside in user space, and as an interface between the user and kernel-level threads.
  2. Kernel threads of control
    this thread is also known as lightweight processes LWP (Light Weight Process). Each process may have a plurality of LWP, like user-level threads, each LWP has its own data structure (e.g., the TCB), which comprises a thread identifier, priority, status, in addition to other local store stack and . They can also share resources owned by the process. LWP may be obtained by calling system services provided by the kernel, so that when a user-level threads running, as long as it is connected to a LWP, at which point it will have all the attributes of a kernel thread support.
    The use of lightweight processes as an intermediate system
Published 107 original articles · won praise 68 · views 7756

Guess you like

Origin blog.csdn.net/weixin_43092232/article/details/105245669