Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

多行程共享資源的互斥訪問:跨行程 pthread 互斥鎖

pthread 的互斥鎖預設只在單一行程內有效。要讓 fork 出來的父子行程共用同一把鎖,必須做兩件事:把鎖放在共享記憶體裡,並明確把它的屬性設成「行程間可共享」。

 #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <pthread.h>
pthread_mutex_t* g_mutex; //創建共享的mutex
void init_mutex(void)
{
 int ret;
 //g_mutex一定要是進程間可以共享的,否則無法達到進程間互斥
 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);
 }
 //設置attr的屬性
 pthread_mutexattr_t attr;
 pthread_mutexattr_init(&attr);
 //一定要設置為PTHREAD_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\n";
 char str2[]="this is father process\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));
}

關鍵在哪裡

mmap 搭配 MAP_SHARED | MAP_ANONYMOUS 配置出一塊父子行程共用的匿名記憶體,鎖就住在這塊記憶體上;若用 MAP_PRIVATE,fork 後各行程持有的是複本,互斥就完全失效。

第二個關鍵是 pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)。少了這一步,即使鎖位於共享記憶體,pthread 仍會以行程內使用的前提來實作它。

子行程刻意 sleep 10 秒,父行程 sleep 2 秒後才嘗試加鎖——如果跨行程互斥真的生效,父行程會被擋住直到子行程解鎖。最終 tmp 檔案的內容會是子行程的敘述排在父行程之前:

this is child process
this is father process

順序若反了,就代表鎖沒有真正發揮作用。最後別忘了 munmap 歸還映射。

Copyright © Linux教程網 All Rights Reserved