在共享内存中锁定互斥锁

Lock mutex in shared memory

我正在尝试在 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));  
}  

问题是我必须在调用 pthread_mutex_lock 之后调用 msync 吗?

不,您不需要调用 msync()。该函数将映射内存刷新到磁盘,但您可能并不关心这一点:您关心同一台机器上的其他程序将看到相同的互斥锁状态。只要其中 none 个崩溃,它们就会崩溃。我想如果您的程序无论如何都会崩溃,您会重置互斥量。

将映射内存刷新到磁盘与 运行 程序是否会看到对该内存的更改无关——就像它与写入更改的同一程序是否能够看到一样阅读它们。