【发布时间】:2020-04-21 04:29:11
【问题描述】:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(int argc,char *argv[]){
//pthread_mutex_init,set process_shared
pthread_mutex_t lock;
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_setpshared(&mutexattr,PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&lock,&mutexattr);
pid_t pid;
int status;
pid = fork();
if(pid < 0)
{
perror("fork is error\n");
exit(EXIT_FAILURE);
}else if(pid == 0){
//child process get the mutex lock
pthread_mutex_lock(&lock);
//know who first get the lock
printf("child lock:pid = %d,ppid = %d\n",getpid(),getppid());
sleep(5);
pthread_mutex_unlock(&lock);
printf("child unlock:pid = %d,ppid = %d\n",getpid(),getppid());
}else{
//father process get the mutex lock
pthread_mutex_lock(&lock);
//know who first get the lock
printf("father lock:pid = %d,ppid = %d\n",getpid(),getppid());
sleep(5);
pthread_mutex_unlock(&lock);
printf("father unlock:pid = %d,ppid = %d\n",getpid(),getppid());
wait(&status);
if(WIFEXITED(status))
{
printf("child is finish,status: %s\n",WEXITSTATUS(status));
}
if(WIFSIGNALED(status))
{
printf("child is finish,status: %s\n",WTERMSIG(status));
}
}
return 0;
}
这段代码显示:父进程和子进程同时获得一把锁,但是pthread_mutexattr_setpshared描述一个进程获得一把锁的函数,代码错误。
The pthread_mutexattr_getpshared() function shall obtain the value of the process-shared attribute from the attributes object referenced by attr. The pthread_mutexattr_setp_shared() function shall set the process-shared attribute in an initialized attributes object referenced by attr.
The process-shared attribute is set to PTHREAD_PROCESS_SHARED to permit a mutex to be operated upon by any thread that has access to the memory where the mutex is allocated,
even if the mutex is allocated in memory that is shared by multiple processes. If the process-shared attribute is PTHREAD_PROCESS_PRIVATE, the mutex shall only be operated upon
by threads created within the same process as the thread that initialized the mutex; if threads of differing processes attempt to operate on such a mutex, the behavior is unde
fined. The default value of the attribute shall be PTHREAD_PROCESS_PRIVATE
【问题讨论】:
-
为了确定,检查
pthread_mutexattr_init和pthread_mutexattr_setpshared以及所有pthread_*函数的返回值。哦,&lock必须指向两个进程都可以访问的内存区域。当你fork有两个&locks -
使用此代码时,PTHREAD_PROCESS_SHARED 或 PTHREAD_PROCESS_PRIVATE 有相同的结果,我尝试使用 mmap 函数,&lock 必须指向两个进程都可访问的内存区域,但 PTHREAD_PROCESS_SHARED 或 PTHREAD_PROCESS_PRIVATE 有相同的结果,我不知道为什么,谢谢你回答我的问题