Linux semaphore Practice (1)

Source: Internet
Author: User
Tags mutex semaphore

synchronization and mutual exclusion of processes

Sequential programs and Concurrency program features

Sequential programs

Concurrent Programs

Sequential nature

Sharing of

Sealing: (Sealing of operating environment)

Concurrency of

Certainty

Randomness

Repeatability

Process Mutex

Because processes require shared resources, and some are mutually exclusive, the processes compete to use these resources, and the process's relationship is mutually exclusive to the process.

Some resources in the system are allowed to be used by only one process at a time, which is called a critical or mutex resource.

A program segment that involves mutually exclusive resources in a process is called a critical section .

Mutex example

Note: If at this time the number of votes x=1,a process and B process at the same time to seize the critical resource X, the implementation of X--, will appear x<0 situation, this situation is certainly unreasonable, the number of votes may not be less than 0;



 


Process synchronization

Process synchronization refers to the need for multiple processes to work together to accomplish a task.

Synchronization examples

Note: Only the driver P1 and the conductor P2 cooperate with each other, in order to complete, the driver to drive and ticket sales process

the generation and release of deadlocks

A deadlock is a phenomenon in which multiple processes wait for each other's resources, and do not release their resources until they are available to them, thus causing a cyclic wait. If all the processes are waiting for something that cannot happen , the process is deadlocked.

The necessary conditions for deadlock generation

1) Mutually exclusive conditions

The process uses the resource in an exclusive, that is, for a period of time a resource is occupied by only one process.

2) Request and hold conditions

When a process is blocked by requesting a resource, it remains in place for the resources that have been obtained .

3) inalienable conditions

The resources that the process has obtained cannot be stripped until it is exhausted and can only be released by itself when it is exhausted.

4) Loop Wait condition

Each process consists of a closed ring chain, each of which waits for the resources occupied by the next process

Prevent deadlock method

Resource one-time allocation (breach request and hold condition)

Deprivation of resources (destruction of inalienable conditions)

Orderly allocation of resources (destruction of cyclic wait conditions)

Deadlock avoidance

Several strategies for preventing deadlocks can seriously damage system performance. Therefore, when the deadlock is avoided, a weaker limit is applied to achieve satisfactory system performance.

Because the process is allowed to request resources dynamically, in a policy that avoids deadlocks. Therefore, the system pre-calculates the security of resource allocation before allocating resources. If this allocation does not cause the system to enter an unsafe state, the resource is assigned to the process; otherwise, the process waits. One of the most representative of the avoidance deadlock algorithm is the banker algorithm.

Signal Volume

The semaphore and P, V primitives are presented by Dijkstra (Dijkstra)


Mutex: P, V in the same process

Synchronization: P, V in different processes


Signal magnitude value meaning

S>0:s indicates the number of available resources

S=0: Indicates no resources available, no wait process

s<0:| S| indicates the number of processes waiting in the queue

PV operation


struct semaphore{    int value;    POINTER_PCB queue;} P Primitive P (s) {    --s.value;    if (S.value < 0)//means no idle resource    {        Sets the current process to blocked state;        Insert the current process's PCB into the appropriate blocking queue S.queue end;}    } V Primitives V (s) {    ++s.value;    if (s.value <= 0)//indicates that there is a process in the blocking state    {        wakes up a process waiting in the blocking queue s.queue, and resets it to the ready state;        Insert it into the ready queue;    }}

semaphore API

Linux maintains data structures for semaphores

struct semid_ds{    struct ipc_perm sem_perm;  /* Ownership and Permissions */    time_t          sem_otime;/* Last Semop time */    time_t          sem_ctime;/* Last Change T IME */    unsigned long   sem_nsems; */* No. of semaphores in Set */};

Semaphore Set function

#include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> int semget (key_t key, int nsems, int se  MFLG); int semctl (int semid, int semnum, int cmd, ...); int semop (int semid, struct sembuf *sops, unsigned nsops);

Semget function

Function: Used to create and access a semaphore set

Prototype

int Semget (key_t key, int nsems, int semflg);

Parameters

Key: Signal set key (key)

Nsems: number of signals in the signal set

SEMFLG: Consists of nine permission flags, which are used in the same way as when creating files using the mode pattern flag

return value:

Successfully returns a non-negative integer, which is the identifier of the signal set ; failure return-1

Practice int Main () {    int semid = Semget (0x12345670,1,0666| Ipc_creat);    if (Semid = =-1)    {        if (errno = = eexist)        {            err_exit ("eexist");        }        else        {           err_exit ("Semget error");        }    }    else    {        cout << "semget OK" << Endl;    }    return 0;}

Shmctl function

Function: Used to control the semaphore set

Prototype

int semctl (int semid, int semnum, int cmd, ...);

Parameters

SEMID: Signal set identification code returned by Semget

Semnum: sequence number of signal concentration signals

CMD: Action to be taken (value below)

The last parameter differs depending on the command

return value:

Successful return 0, failure return-1

Man-page       Semctl ()  performs  the  control operation specified by cmd on the System V semaphore set Identifie D by Semid, or to the semnum-th semaphore of that set.  (The semaphores in a set is numbered starting at 0.)       This  function  has a three or four arguments, and depending on cmd.  When there is four, the fourth has the type Union Semun.  The calling program must define this union as follows:union semun{    int              val;    /* Value for Setval */    struct semid_ds *buf;    /* Buffer for Ipc_stat, Ipc_set */    unsigned short  *array;  /* Array for GETALL, SETALL */    struct seminfo  *__buf;  /* Buffer for Ipc_info                                           (linux-specific) */};

Practice: setvalunion mysemun{    int              val;    Value for setval//    struct semid_ds *buf;    Buffer for Ipc_stat, ipc_set//    unsigned short  *array;  Array for GETALL, setall//    struct seminfo  *__buf;  Buffer for Ipc_info (linux-specific)//};int main () {    int semid = Semget (0x12345670,1,0666| Ipc_creat);    if (Semid = =-1)    {        err_exit ("Semget error");    }    Union Mysemun SetValue;    Setvalue.val = 15764;    if (Semctl (semid,0,setval,setvalue)! = 0)    {        err_exit ("Semctl setval error");    }    int returnvalue = Semctl (semid,0,getval,0);    cout << "returnvalue =" << returnvalue << Endl;    return 0;}

Semop function

Function: Used to manipulate a semaphore set

Prototype

int semop (int semid, struct sembuf *sops, unsigned nsops);

Parameters

Semid: Is the identifier of the semaphore, which is the return value of the Semget function

SOPs: is a pointer to an array of structures

Nsops: Number of semaphores

return value:

Successful return 0, failure return-1

Man-page Sample Code    struct SEMBUF sops[2];    int semid;    /* Code to set Semid omitted */    sops[0].sem_num = 0;        /* Operate on Semaphore 0 */    sops[0].sem_op = 0;         /* Wait for value to equal 0 */    SOPS[0].SEM_FLG = 0;    Sops[1].sem_num = 0;        /* Operate on Semaphore 0 */    sops[1].sem_op = 1;         /* Increment Value by one */    SOPS[1].SEM_FLG = 0;    if (Semop (Semid, SOPs, 2) = =-1)    {        perror ("Semop");        Exit (exit_failure);    }

The SEMBUF structure reference is as follows:

struct sembuf{    unsigned short sem_num;  /* Semaphore number */short          sem_op;   /* Semaphore operation */short          sem_flg;  /* Operation flags * *};

Sem_num is the number of semaphores (starting from 0).

SEM_OP is the signal amount of a PV operation added and minus the value, generally only use two values, one is "1", that is, p operation, waiting for the semaphore to become available, and the other is "+1", that is, v operation, The amount of signal emitted has become available;

The two values of Sem_flag are ipc_nowait or Sem_undo

Linux semaphore Practice (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.