Linux communication--Building process communication System-V message queue | semaphore

Article directory

Table of contents

1. Message queue

2. Signal amount

1. Mutually exclusive

2. Signal amount



1. Message queue

  • Message queues provide a way to send chunks of data from one process to another
  • Each data block is considered to have a type, and data blocks received by the receiver process can have different type values.
  • IPC resources must be deleted, they will not be cleared automatically with the process, and the lifecycle will depend on the kernel.
  • For example, process A, B, A sends a signal to B, and the code is 2. The 2 signal is put into the message queue, and B finds the corresponding data block according to the code.

2. Signal amount

Semaphores are mainly used for synchronization and mutual exclusion.

1. Mutually exclusive

Resources that can be seen by any process are called public resources. However, some resources need to be used mutually exclusive. For example, if one process reads and another process writes, reading is not allowed before the writing is completed. Therefore, various processes need to compete to use these resources.

The mutual exclusion mechanism is: at any time, only one execution flow is allowed to access public resources (can be locked)

  • Certain resources in the system are only allowed to be used by one execution flow at a time. Such resources are called critical resources or mutually exclusive resources.

  • The program segment that accesses critical resources in a process is called a critical section.
  • Atomicity: There are only two definite states 0/1

2. Signal amount

The essence of a semaphore is a counter (int count), used to describe the number of resources. The semaphore is similar to buying tickets for a movie. It is a reservation mechanism. After the ticket is successfully purchased, the seat is locked. The execution flow wants to access a sub-resource in the critical resource (there are many critical resources in the critical section). Before entering the critical section, it must first apply for a semaphore (the process applies for a semaphore), exit the critical section, and release the semaphore.

if(count > 0)
{
    //...执行
}

else
{
    //...挂起
}

Therefore, all processes must first see the semaphore, which is a shared resource.

If count = 1, it is called a binary semaphore, completing the mutually exclusive function.


Guess you like

Origin blog.csdn.net/jolly0514/article/details/132585636