Semaphores

  

Semaphores are used to synchronize various operations between processes 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 acts as counter.  Its value depends on the number of resources there are to share.  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 the semaphore value to 1. Thereby by allowing one other process access.

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.

Process A

Process B Kernel

Semaphore
0 or 1

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 the middle.

Semaphore Set:

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

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 the semaphore'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.

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); 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

The parameter:
  

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);

Embedded Training @ Manvish e-tech

Semaphore – Program 1
Sempro1.c
#include </sys/types.h> #include <.sys/ipc.h> 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 ipcs –s at the prompt to verify */
Embedded 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 the semaphore is already created Semaphore with exclusivity  Semaphore can be created by any process using an IPC_EXCL flag  If any other process try to create the same semaphore, semget() system call returns negative number indicating an error.  Ex:
semid= semget(key,nsem,IPC_CREAT|0666|IPC_EXCL);
Embedded 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

Embedded Training @ Manvish e-tech

Setting and Getting Semaphore values

After the semaphore set is created, we need to initialize the value of the semaphores 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 SETVAL option
/* 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); }

Embedded Training @ Manvish e-tech

Setting and Getting Semaphore values
/* 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); }

Embedded Training @ Manvish e-tech

Setting and Getting Semaphore values

Getting Semaphore values:

Semaphore values can be read using GETVAL option in semctl() 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); }
Embedded Training @ Manvish e-tech

Setting and Getting Semaphore values
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 values to variable val.

Embedded Training @ Manvish e-tech

Setting and Getting Semaphore values
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.

Embedded Training @ Manvish e-tech

Usage of Resource

A semaphore is basically used by different processes to synchronize access to a resource Access to resource is actually depends on what value the user has assigned Example:  If the semaphore has value 1, it may indicate that a certain resource is in use by some other process  If the semaphore has a value 2, it may indicate that the resource 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 the semaphore

Embedded 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); }
Embedded 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
Embedded 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 common resource at same time. Atomicity provides access to one particular resource by one process at a time. That is, if one of the operations can’t be done, none will be. Linux provides structure sembuf and function semop() to provide atomicity

Embedded 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 subsemaphore. The semaphores are indicated as 0,1,2,3,4….. sem_op is a value that defines the operation we want performed on the semaphore. Using this value we can define whether we want to capture the resource or release it. sem_flag defines the step to take if the semaphore is already in use by another process. If sem_flag=IPC_NOWAIT allows the process to carry on with some other task if the resource is not available. if flag=SEM_UNDO, it resets the value of semaphore to the Embedded Training @ Manvish e-tech original.

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 value of the semaphore is the same or greater, then the operation is performed successfully.  If the absolute value of the semaphore is less than 2 then the semop() will wait till the value becomes 2 or greater.  If the value of the member sem_op is positive (eg. 5) then this value will be added to the value of the semaphore. Ex: If the semaphore 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).
Embedded Training @ Manvish e-tech

Semaphore - Example
#include <sys/types.h> #include<sys/ipc.h> #include<sys/sem.h>
main() int semid,pid,val; struct sembuf sop; semid=semget(0x20, 1, IPC_CREAT|0666); semctl(semid,0,SETVAL,3); val=semctl(semid,0,GETVAL,0); printf(“Value of semaphore 1st time %d\n”,val); pid=fork() if (pid==0) { 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”); } else { sleep(1); val=semctl(semid,0,GETVAL,0); printf(“Value of sem 2nd time%d\n”,val); sleep(5); val=semctl(semid,0,GETVAL,0); printf(“Value of Sem 3rd time%d\n”,val); } }

Embedded Training @ Manvish e-tech

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; }

Embedded Training @ Manvish e-tech

Sign up to vote on this title
UsefulNot useful