In the third quarter - Lesson 16 - Semaphore mutex programming

Lesson 16 - Semaphore mutex programming

 

16.1 bar public issue (problem introduced)

1. Problem Description

That which we take a small example. In a classroom, there is a bar public, A classmate to write "math exam", B students to write "English class is canceled." But there is a time, A classmate wrote only three words "math" did not have time to write the contents back went out, but this time to B students wrote "English class is canceled." Such seems to allow students to become "math class English class Cancel" to other students in the class causing ambiguity.

This is what we are talking simultaneously access a resource, resulting in confusion of data. If there are multiple processes simultaneously access a resource, it will also cause this problem.

2. procedural issues

A classmates process instead of A, B students with the process instead of B, bar public use files instead. We previously off course folder inside the establishment student1.c and student2.c.

Note: This is a join operation --- ctil + shift + t can finish copying a different command bar window.

stduent1 program:

#include<unistd.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

#include<stdio.h>

void main()

{

         int fd = 0;

         0 // Open the file

         fd = open("./board.txt",O_RDWR|O_APPEND,0777);

         // 1. Write "math" to the bulletin board inside the file

         write(fd,"math class",11);

         // 2. Pause rest

sleep(5);

         // 3. Bulletin board file is written to the "Cancel"

         write(fd,"is cancel",11);

         close(fd);

}

stduent2 program:

#include<unistd.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

#include<stdio.h>

void main()

{

         int fd = 0;

         0 // Open the file

         fd = open("./board.txt",O_RDWR|O_APPEND,0777);

         // 1. Write "English class examination" to the bulletin board inside the file

         write(fd,"English exam",20);

         // 2. Close the file

         close(fd);

}

The result: we opened two interrupts run in a terminal: ./ stduent1,5s inherent in another terminal run ./stduent2. We look ahead to create good board.txt files appear as: math class English exam   


;is cancel 

 

 

3. semaphore concept

To be able to access the program is a chaotic situation will not arise, we can say a little white, like a toilet, as there is someone to enter the signage was displayed, even if a very long time. So as to achieve mutually exclusive access. This concept is a semaphore.

l concept: semaphore (aka: lights) and other inter-process communication is not the same way, the main purpose is the protection of critical resources (mutual exclusion) . The process can determine whether it has access to some shared resources. In addition to control, but also can be used to synchronize processes.

l Category:

Binary semaphore: lights can only take the value 0 or 1;

Counting semaphore: semaphore value can take any non-negative value.        

l amount signal flow:

1) Open the semaphore identifier obtained

2) using the identifier, a series of operations

16.2 Function Learning

1. Create / open semaphore

(1) function name

semget

(2) Function Prototype

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

(3) function-

Get semaphore set (a plurality of signals or signal) identifier (get a semaphore set identifier), when the amount of the key signal is not under, and which contains the IPC_CREAT semflg, set the semaphore is created.

(4) belongs to the header file

#include<sys/types.h>

#include<sys/ipc.h>

#include<sys/sem.h>

(5) Return value

Success: Returns the semaphore identifier set;

Failed: -1.

(6) Parameter Description

l What is the "key" :( file to create the file name, use the file when the file has fd (the above mentioned id number); ipc when objects are created key (a number), when used are identifier ) for a file, we just find the file name, we will be able to find the file id (fd), open the file. For a semaphore (ipc objects) regardless of whether or not to use both with key values, we need to know his "key" that we will be able to open its identifier. This identifier is open ipc objects will be some, the key is whether the open and have not opened. Whether it is a process A or B process, we have to find its semaphore, we must know its "key." When we create a semaphore (it will have after the creation), we specify a key for it. How key to select it (when the ipc object created)? Here we present two methods:

(1) a number of arbitrarily designated

Disadvantages: The number of IPC has been another object (message queues, shared memory) to be used, and that the newly created channel

Will fail when the related amount.

(2) construct a number of possible methods are not used by other objects IPC: Use key_t ftok (char * fname, int id)

This function takes two parameters, the first is the file name, the second is the project id. According to the file name, we can get a number, this number is a text file saved in the file information inside the kernel. This number again, and project id combined to form the key values we want. Produce this number of keys : a digital core to save the file name structure + project id, a number so formed. That is, we know the file name and project id can get ipc key object, know ipc key objects can get ipc identifiers object.

         Each process has a unique identifier of the corresponding key.

key: Open an amount corresponding to the key signal.

semflg: flag, you can take the IPC_CREAT, when the amount is not under key signal, and which contains the IPC_CREAT semflg, set the semaphore is created.

nsems: Create the semaphore set which contains the number of semaphores, is a number.

 

2. Operation semaphore

(1) function name

semop

(2) Function Prototype

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

(3) function-

Semaphore operation amount of inside the set signal.

(4) belongs to the header file

#include<sys/types.h>

#include<sys/ipc.h>

#include<sys/sem.h>

(5) Return value

Success: 0;

Failed: -1.

(6) Parameter Description

semid: semaphore operation to be set (may be a plurality) of the identifier.

sembuf: It contains the following set,

unsigned short sem_num; / * semaphore number * / Number semaphore operation set

short sem_op; / * semphore operation * / positive number indicates the release (1), obtain a negative number (-1), causes the program to wait unsuccessful

short        sem_flg;   /*operation flags*/

nsops: total number of operating the semaphore

sops: performing a semaphore operation what, a pointer corresponding to an operation, if there are three operations, that is, the number of group 3 array.

16.3 integrated example Programming

         A semaphore is acquired prior to use of the blackboard, and the blackboard started. Blackboard when the semaphore's value should be zero. Use finished board release the semaphore, the semaphore becomes 1. A classmate because it is the first to use this semaphore, so to be created by the students A semaphore.

         B students in the use of previously acquired semaphore can be acquired to, direct use. If in the process of acquisition, it was found that the A semaphore is acquired, it waits until the A classmate after use. B students finished using the semaphore, the semaphore is released.

stduent1.c

#include<unistd.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

#include<stdio.h>

#include<sys/ipc.h>

#include<sys/sem.h>

void main()

{

         int fd = 0;

         int semid;

         key_t key;

         struct sembuf sops;

         // Create the semaphore key

         key = ftok ( "/ home", 1); // file name, and a digital manner, may be arbitrarily combined.

         // Create and open semaphore

semid = semget (key, 1, IPC_CREAT); // not the semaphore in the system, parameter IPC_CREAT; // to use a semaphore using a digital 1

 

         0 // Open the file

         fd = open("./board.txt",O_RDWR|O_APPEND,0777);

         //1.1 obtain the semaphore

sops.sem_num = 0; // set our semaphore there is only one signal, a signal sequence our operations must be 0 // Number

         sops.sem_op = -1; // - 1 acquires the semaphore indicates

semop (semid, & sops, 1); // a semaphore operation, with a third parameter; the second parameter indicates what kind of operation performed

         // 1. Write "math" to the bulletin board inside the file

         write(fd,"math class",11);

         // 2. Pause rest

         sleep(10);

         // 3. Bulletin board file is written to the "Cancel"

         write(fd,"is cancel",11);

         // release the semaphore

         sops.sem_num = 0; // first semaphore

         sops.sem_op = 1; // release the semaphore, the operation + 1

         semop(semid,&sops,1);

         close(fd);

}

 

Stduent2.c

#include<unistd.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

#include<stdio.h>

#include<sys/ipc.h>

#include<sys/sem.h>

void main()

{

         int fd = 0;

         int semid;

         key_t key;

         struct sembuf sops;

         // Create the semaphore key

         key = ftok ( "/ home", 1); // ensure that two students with a semaphore operation, the key is the same composition.

         // Open Semaphore collection

         semid = semget(key,1,IPC_CREAT);

         0 // Open the file

         fd = open("./board.txt",O_RDWR|O_APPEND,0777);

         // Get semaphore

         sops.sem_num = 0;

         sops.sem_op = -1;

         semop(semid,&sops,1);

         // 1. Write "English class examination" to the bulletin board inside the file

         write(fd,"English exam",12);

         // release the semaphore

         sops.sem_num = 0;

         sops.sem_op = 1;

         semop(semid,&sops,1);

         // 2. Close the file

         close(fd);

}

The result: when ./student1 and ./student2 when we run in two separate terminals, what we see is supposed to be the first program in the waiting, the second program is also waiting until the first procedures are completed. And the data is not written to confusion. However, we did not expect to see these two. Run B program, instantly ending; data writing is not right. Here we ignore the things we've been doing a hypothesis, that is, the initial value of the semaphore is 1.

The actual value of the semaphore is not necessarily 1, 4,5,6 may be other values.

Here we introduce another function: semctl

Function prototype

int semctl (int semid, int sennum, int cmd, ... / * union semum arg * /); // 10 species, we use this command GETVAL

In the following two commands student.c added: int ret;

     ret = semctl(semid,1,GETVAL);

Its initial value is found: 1;

Here is the program after the change

student1.c

#include<unistd.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

#include<stdio.h>

#include<sys/ipc.h>

#include<sys/sem.h>

void main()

{

         int fd = 0;

         int semid;

         key_t key;

         int ret;

         struct sembuf sops;

         // Create the semaphore key

         key = ftok("/home",1);

         // create and open semaphore collection

         semid = semget(key,1,IPC_CREAT);

         ret = semctl (semid, 0, SETVAL, 1); // initial value to the semaphore: 1

         printf("init value of sem is %d\n",ret);

         0 // Open the file

         fd = open("./board.txt",O_RDWR|O_APPEND,0777);

         //1.1 obtain the semaphore

         sops.sem_num = 0;

         sops.sem_op = -1;

         semop(semid,&sops,1);

         // 1. Write "math" to the bulletin board inside the file

         write(fd,"math class",11);

         // 2. Pause rest

         sleep(10);

         // 3. Bulletin board file is written to the "Cancel"

         write(fd,"is cancel",11);

         // release the semaphore

         sops.sem_num = 0;

         sops.sem_op = 1;

         semop(semid,&sops,1);

         close(fd);

}

student2:

#include<unistd.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

#include<stdio.h>

#include<sys/ipc.h>

#include<sys/sem.h>

void main()

{

         int fd = 0;

         int semid;

         key_t key;

         struct sembuf sops;

         int ret;

         // Create the semaphore key

         key = ftok("/home",1);

         // Open Semaphore collection

         semid = semget(key,1,IPC_CREAT);

         0 // Open the file

         fd = open("./board.txt",O_RDWR|O_APPEND,0777);

         ret = semctl (semid, 0, GETVAL); // look how much the value of the semaphore

         printf("ret is %d\n",ret);

         // Get semaphore

         sops.sem_num = 0;

         sops.sem_op = -1;

         semop(semid,&sops,1);

         // 1. Write "English class examination" to the bulletin board inside the file

         write(fd,"English exam",12);

         // release the semaphore

         sops.sem_num = 0;

         sops.sem_op = 1;

         semop(semid,&sops,1);

         // 2. Close the file

         close(fd);

}

Run Results: Run ./student1 and ./student2 respectively in two terminals. We can see the emergence of waiting. Board.txt contents are: math class is cancel English exam

This is the result we want.

 

Guess you like

Origin www.cnblogs.com/free-1122/p/11351438.html