锁定共享内存中的互斥锁

时间:2015-01-27 06:19:20

标签: c mutex mmap

我正在尝试在mutil多进程程序中使用pthread_mutex_t,我需要在共享内存中锁定互斥锁以进行同步。以下是我复制from的代码。

#include    <stdio.h>  
#include    <stdlib.h>  
#include    <unistd.h>  
#include    <fcntl.h>  
#include    <sys/mman.h>  
#include    <pthread.h>  
pthread_mutex_t* g_mutex;  
void init_mutex(void)  
{  
   int ret;   
   g_mutex=(pthread_mutex_t*)mmap(NULL, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);  
   if( MAP_FAILED==g_mutex )  
   {  
       perror("mmap");  
       exit(1);  
   }  


   pthread_mutexattr_t attr;  
   pthread_mutexattr_init(&attr);  

   //set mutex process shared 
   ret=pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED);  
   if( ret!=0 )  
   {  
       perror("init_mutex pthread_mutexattr_setpshared");  
       exit(1);  
   }  
   pthread_mutex_init(g_mutex, &attr);  
}  
int main(int argc, char *argv[])  
{  
   init_mutex();  
   int ret;      
   char str1[]="this is child process/r/n";  
   char str2[]="this is father process/r/n";  
   int fd=open("tmp", O_RDWR|O_CREAT|O_TRUNC, 0666);  
   if( -1==fd )  
   {  
      perror("open");  
      exit(1);  
   }  
   pid_t pid;  
   pid=fork();  
   if( pid<0 )  
   {  
       perror("fork");  
       exit(1);  
   }  
   else if( 0==pid )  
   {  
       ret=pthread_mutex_lock(g_mutex);  
       if( ret!=0 )  
       {  
           perror("child pthread_mutex_lock");  
       }  
       sleep(10); 
       write(fd, str1, sizeof(str1));  
       ret=pthread_mutex_unlock(g_mutex);    
       if( ret!=0 )  
       {  
           perror("child pthread_mutex_unlock");  
       }     
    }  
    else  
    {  
        sleep(2);   
        ret=pthread_mutex_lock(g_mutex);  
        if( ret!=0 )  
        {  
            perror("father pthread_mutex_lock");  
        }  
        write(fd, str2, sizeof(str2));  
        ret=pthread_mutex_unlock(g_mutex);    
        if( ret!=0 )  
        {  
            perror("father pthread_mutex_unlock");  
        }                 
    }  
    wait(NULL);  
    munmap(g_mutex, sizeof(pthread_mutex_t));  
}  

我打电话msync后,是否需要拨打pthread_mutex_lock

1 个答案:

答案 0 :(得分:0)

不,您无需致电msync()。该函数将映射的内存刷新到磁盘,但您可能并不关心:您关心同一台计算机上的其他程序将看到相同的互斥锁状态。他们会,只要他们都没有崩溃。我想如果你的程序崩溃了,你就会重置互斥锁。

将映射内存刷新到磁盘与运行程序是否会看到对该内存的更改无关 - 正如它与编写更改的相同程序是否能够读取它们无关。