【问题标题】:Lock mutex in shared memory在共享内存中锁定互斥锁
【发布时间】:2015-01-27 06:19:20
【问题描述】:

我正在尝试在 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 吗?

【问题讨论】:

    标签: c mutex mmap


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,这就是我关心的。
    猜你喜欢
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2012-06-29
    • 2013-12-17
    相关资源
    最近更新 更多