7 Semaphores

download 7 Semaphores

of 22

Transcript of 7 Semaphores

  • 8/22/2019 7 Semaphores

    1/22

    Embedded Training@Manvish e-tech

    Semaphores

    Semaphores are used to synchronize various operations betweenprocesses in case of multitasking system

    Semaphores allow various process to share resources synchronously

    What is a Semaphore?

    A semaphore is a variable that contains an integer value actsas counter.

    Its value depends on the number of resources there are toshare.

    Ex: If there is only one file/resource to be shared between processes, then

    the semaphore can have a value 0 or 1. A 0 initialized semaphore signifies that the resource (file) is in use and

    therefore all other processes would have to wait.

    The moment the process that has access to the file finishes, it sets thesemaphore value to 1. Thereby by allowing one other process access.

  • 8/22/2019 7 Semaphores

    2/22

    Embedded Training@Manvish e-tech

    Semaphores Contd..

    Considering that a semaphore has to be shared by various processes, it has

    to be a global variable.

    Semaphore value is always stored in kernel to allow processes to access

    globally.

    Kernel

    Semaphore

    Process A Process B

    0 or 1

  • 8/22/2019 7 Semaphores

    3/22

    Embedded Training@Manvish e-tech

    Semaphore contd.

    Semaphore allows processes to synchronize by testing and setting the value in a

    single atomic operation. This means that:

    The process that tests the value of a semaphore is then sets it to a different value(based on the test).

    And it guarantees that no other process will interfere with the operation in themiddle.

    Semaphore Set:

    A semaphore set is a structure that stores a group of semaphorestogether and possibly allows the process to commit a transaction onpart or all of the semaphores in the set together

  • 8/22/2019 7 Semaphores

    4/22

    Embedded Training@Manvish e-tech

    Semaphore Operations

    There are two types of operations carried on semaphore:

    Wait

    Signal

    Wait:

    First checks if the semaphore's value equals some number. If it does, it decreases its value and returns.

    If it does not, the operation blocks the calling process until thesemaphore's value reaches the desired value.

    Signal:

    A signal operation increments the value of the semaphore possibly awakening one or more processes that are waiting on the

    semaphore.

  • 8/22/2019 7 Semaphores

    5/22

    Embedded Training@Manvish e-tech

    Creating a Semaphore

    Semaphore must be created before using to synchronize the

    processes

    System call semget() is used to create a semaphore set.

    Syntax: semid=semget(key, nsem, flags);

    The parameter: key- It is the ID of the semaphore set

    nsem It is the number of semaphores to have in a given set

    flags - Used to define access permission mode and a few options

  • 8/22/2019 7 Semaphores

    6/22

    Embedded Training@Manvish e-tech

    Semget() example/* The header files sys/types.h and sys/ipc.h must be included for semaphore operations

    */

    /* ID of the semaphore set. */

    int sem_set_id_1;

    int sem_set_id_2;

    /* create a semaphore set with ID (Key) 2, only 1 semaphore */

    /* in the set, with access only to the owner */

    sem_set_id1=semget(2,1,IPC_CREAT|0600);

    if (sem_set_id_1 == -1) {

    perror("main: semget");

    exit(1);

    /* create a semaphore set with ID (key) 250, three semaphores */

    /* in the set, with access only to the owner. */

    sem_set_id_2 = semget(250, 3, IPC_CREAT | 0600);

    if (sem_set_id_2 == -1) {

    perror("main: semget");

    exit(1);

  • 8/22/2019 7 Semaphores

    7/22Embedded Training@Manvish e-tech

    SemaphoreProgram 1

    Sempro1.c

    #include

    #include

    main()

    {

    int semid, key, nsem;

    key=(key_t) 0x20;

    nsem=1;

    semid= semget(key,nsem,IPC_CREAT|0666);

    if(semid == -1)

    {

    printf(\n Error creating semaphore);

    }

    else

    printf(Semaphore created with ID:%d\n, semid);

    }

    /* try the above program with nsem = 2,3 5, 10 100 etc and observe the results */

    / * Run ipcss at the prompt to verify */

  • 8/22/2019 7 Semaphores

    8/22Embedded Training@Manvish e-tech

    Semaphore ID and its exclusivity

    Semaphores can be created with or without exclusivity

    Semaphore without exclusivity:

    Once the semaphore is created by a process an ID will assigned

    If the same semaphore is created by some other process, then

    the process will get the previous ID, indicating that thesemaphore is already created

    Semaphore with exclusivity

    Semaphore can be created by any process using an IPC_EXCLflag

    If any other process try to create the same semaphore,semget() system call returns negative number indicating anerror.

    Ex:

    semid= semget(key,nsem,IPC_CREAT|0666|IPC_EXCL);

  • 8/22/2019 7 Semaphores

    9/22Embedded Training@Manvish e-tech

    Deleting semaphore

    Semaphore which is already created can be removed if no

    longer required

    Semaphore can be deleted using the system call semctl()

    The syntax is:

    semctl(semid,0,IPC_RMID,0);

    semid is the ID of the semaphore to delete

    IPC_RMID indicates to remove the semaphore of ID

    semid

  • 8/22/2019 7 Semaphores

    10/22Embedded Training@Manvish e-tech

    ett ng an ett ng emap ore

    values

    After the semaphore set is created, we need to initialize the value of thesemaphores in the set.

    System call semctl() is used to set and get values of semaphore

    Set or Initialise the semaphore:

    Semaphores can be initialized using SETVALoption

    /* use this to store return values of system calls. */

    int rc;

    /* initialize the first semaphore in our set to '3'. */

    rc = semctl(semid, 0, SETVAL, 3);

    if (rc == -1) {

    perror("main: semctl");

    exit(1);

    }

  • 8/22/2019 7 Semaphores

    11/22Embedded Training@Manvish e-tech

    ett ng an ett ng emap orevalues

    /* initialize the second semaphore in our set to '6'. */

    rc = semctl(semid, 1, SETVAL, 6);

    if (rc == -1) {

    perror("main: semctl");

    exit(1);

    }

    /* initialize the third semaphore in our set to '0'. */

    rc = semctl(semid, 2, SETVAL, 0);

    if (rc == -1) {

    perror("main: semctl");

    exit(1);

    }

    tt tt

  • 8/22/2019 7 Semaphores

    12/22Embedded Training@Manvish e-tech

    ett ng an ett ng emap orevalues

    Getting Semaphore values:

    Semaphore values can be read using GETVAL option insemctl() system call/* The variable retval collects the semaphore value */

    main()

    {

    int retval,rc;

    int semid;

    semid=semget(0x20,1, IPC_CREAT|0666);

    /* initialize the first semaphore in our set to '3'. */

    rc = semctl(semid, 0, SETVAL, 3);

    if (rc == -1) {perror("main: semctl");

    exit(1);

    }

    retval=semctl(semid,0,GETVAL,0);

    printf(Value returned is %d\n, retval);

    }

    tt tt

  • 8/22/2019 7 Semaphores

    13/22Embedded Training@Manvish e-tech

    ett ng an ett ng emap orevalues

    Example:

    main()

    {

    int semid;

    unsigned short val[5];

    semid=semget(0x20,5,0666|IPC_CREAT);

    semctl(semid,0,SETVAL,1);

    semctl(semid,1,SETVAL,2);

    semctl(semid,2,SETVAL,3);

    semctl(semid,3,SETVAL,4);

    semctl(semid,4,SETVAL,5);

    semctl(semid,0,GETALL,val);

    printf(val 1:%d val2:%d val3:%d val4:%d val5:%d\n, val[0], val[1], val[2], val[3],val[4]);

    The above examples creates five sub-semaphore . GETALL will read all semaphore valuesto variable val.

    tt tt

  • 8/22/2019 7 Semaphores

    14/22Embedded Training@Manvish e-tech

    ett ng an ett ng emap orevalues

    Example:

    main()

    {

    int semid;

    static unsigned short val[5]={1,2,3,4,5}, val1[5];

    semid=semget(0x20,5,0666|IPC_CREAT);

    semctl(semid,0,SETALL,val);

    semctl(semid,0,GETALL,val);

    printf(val1:%d val2:%d val3:%d val4:%d val5:%d\n, val1[0], val1[1],

    val1[2], val1[3], val1[4]);

    The above examples creates five sub-semaphore . GETALL will read all

    semaphore values to variable val.

  • 8/22/2019 7 Semaphores

    15/22Embedded Training@Manvish e-tech

    Usage of Resource

    A semaphore is basically used by different processes to synchronizeaccess to a resource

    Access to resource is actually depends on what value the user hasassigned

    Example:

    If the semaphore has value 1, it may indicate that a certainresource is in use by some other process

    If the semaphore has a value 2, it may indicate that theresource is free to be used by some other processes

    Using the semctl() function we can find out which process has set the

    value of a semaphore A value of GETPID passed to the semctl() will provide PID

    The PID is the process ID which has set the value of thesemaphore

  • 8/22/2019 7 Semaphores

    16/22Embedded Training@Manvish e-tech

    Usage of Resource contd.

    Example: Set value

    main()

    {

    int semid;

    semid=semget(0x20,1,IPC_CREAT|0666);

    semctl(semid,0,SETVAL,1);

    }

    Get PID

    main()

    {int semid,retval;

    semid=semget(0x20,1,IPC_CREAT|0666);

    retval=semctl(semid,0,GETPID,0);

    printf(\n The PID=%d, retval);

    }

  • 8/22/2019 7 Semaphores

    17/22Embedded Training@Manvish e-tech

    Across Processes

    Using Semaphores between processes Let us consider 2 processes communicating through the

    Semaphores. The steps must be as follows:

    Steps at Process A

    Create a Semaphore Set the Semaphore Flag

    Work with the resource

    Steps at Process B

    Get the Semaphore ID Check the Semaphore Flag

    If Flag is set wait till its free

    When its free, set the Flag

    Work with the resources

  • 8/22/2019 7 Semaphores

    18/22Embedded Training@Manvish e-tech

    Atomicity

    The values initialized in semaphores are interpreted by

    different processes to ascertain whether they have access to a

    particular resource or not.

    The resource available to all processes must be synchronized

    such that no two or more processes are accessing the commonresource at same time.

    Atomicity provides access to one particular resource by one

    process at a time. That is, if one of the operations cant be

    done, none will be. Linux provides structure sembufand function semop() to

    provide atomicity

  • 8/22/2019 7 Semaphores

    19/22Embedded Training@Manvish e-tech

    Semaphore struct and semop()

    Structure sembuf:struct sembuf {

    unsigned short sem_num; /* semaphore number */

    short sem_op; /* Semaphore operation*/

    short sem_flag; /* Operation flag*/

    };

    sem_num is the number that is associated with a sub-semaphore. The semaphores are indicated as 0,1,2,3,4..

    sem_op is a value that defines the operation we want performedon the semaphore. Using this value we can define whether wewant to capture the resource or release it.

    sem_flag defines the step to take if the semaphore is already inuse by another process. If sem_flag=IPC_NOWAIT allows theprocess to carry on with some other task if the resource is notavailable.

    if flag=SEM_UNDO, it resets the value of semaphore to theoriginal.

  • 8/22/2019 7 Semaphores

    20/22Embedded Training@Manvish e-tech

    Semaphore struct and semop()

    Function sem_op():

    Syntax:

    semop(semid, &sop, no_times);

    semid: Semaphore ID

    &sop: It is the struct sembuf structure

    no_times: No. of structures it has to go through to perform operation The function sem_op() sets or resets the value of the semaphore.

    It returns a value which indicates success or failure.

    Following operations are performed based on the values:

    If the value is negative number (eg 2) and if the absolute valueof the semaphore is the same or greater, then the operation isperformed successfully.

    If the absolute value of the semaphore is less than 2 then thesemop() will wait till the value becomes 2 or greater.

    If the value of the member sem_op is positive (eg. 5) then thisvalue will be added to the value of the semaphore. Ex: If thesemaphore value is 1, then the semop() would make it 6.

    If the value of the member sem_op being 0 and the value of the

    semaphore is also 0 then semop() will perform (special case).

  • 8/22/2019 7 Semaphores

    21/22Embedded Training@Manvish e-tech

    Semaphore - Example#include

    #include#include

    main()

    int semid,pid,val; else

    struct sembuf sop; {

    semid=semget(0x20, 1, IPC_CREAT|0666); sleep(1);

    semctl(semid,0,SETVAL,3); val=semctl(semid,0,GETVAL,0);

    val=semctl(semid,0,GETVAL,0); printf(Value of sem 2nd time%d\n,val);

    printf(Value of semaphore 1st time %d\n,val); sleep(5);

    pid=fork() val=semctl(semid,0,GETVAL,0);

    if (pid==0) printf(Value of Sem 3rd time%d\n,val);

    { }

    printf(Child doing semop with 2\n); }

    sop.sm_num=0;

    sop.sem_op=-2;

    sop.sem_flg=SEM_UNDO;

    semop(semid,&sop,1);

    printf(Child in critical section \n);

    sleep(5);

    printf(Child is out of critical section\n);}

  • 8/22/2019 7 Semaphores

    22/22E b dd d T i i @ M i h h

    Summary

    Main functions used in semaphore

    semget()

    semctl() [RM_IPC, SETVAL, GETVAL, SETALL, GETALL]

    semop() [flags: IPC_NOWAIT, SEM_UNDO]

    Semaphore structure

    struct sembuf {

    ushort sem_num;

    short sem_op;

    short sem_flag;

    }