Translate

Chủ Nhật, 4 tháng 12, 2016

Shared memory introduction

Created by Thomas.


Shared memory is the fastest form of IPC. Once the memory is mapped into the address space of processes that are sharing the memory region, no kernel action is needed.  However, it needs synchronization between the sharing processes.

Below example shows client-server using shared memory. Noted that shared memory appears both at address space of client and server.



Take a example about the case that the parent process and child process can not shared a global variable 'count'.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
int count = 0;
 
int main(int argc, char **argv)
{
  int i,nloop=300,zero=0,*ptr;
  sem_t *mutex;
 
  // assign value of 1 to semaphore
  //if ((mutex = sem_open("semap", O_CREAT | O_EXCL, 0644, 1)) == SEM_FAILED) {
  if ((mutex = sem_open("semap", O_CREAT, 0644, 1)) == SEM_FAILED) {
 perror("semaphore initilization");
    exit(0); 
  }
  sem_unlink("semap");
   
  if (fork() == 0) {
   for (i =0; i < nloop; i++) {
    sem_wait(mutex);
    printf("child:%d\n", count++);
    sleep(2);
    sem_post(mutex);
    sleep(2);
   }
  }
   
  /* back to parent process */
  for (i = 0; i < nloop; i++) {
    sem_wait(mutex);
    printf("parent: %d\n", count++);
    sem_post(mutex);
 sleep(1);
  }
  exit(0);
}


The output is below.
















In above code, to synchronize access the count variable, we use a named mutex. This mutex is truly shared by parent and child. However, 'count' is not shared memory. Both parent and child has their own memory space of 'count'. That is reason parent and child increase 'count' independently.

Next, we will check how to use shared memory for 'count' global variable.

Không có nhận xét nào:

Đăng nhận xét