linux pthread_mutexattr_setpshared не работает, - PullRequest
0 голосов
/ 21 апреля 2020
#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

1 Ответ

2 голосов
/ 22 апреля 2020

родительский процесс и дочерний процесс получают одну блокировку одновременно

Это потому, что они не разделяют память, в которой находится блокировка: после fork, каждый процесс имеет свою собственную копию (стека) памяти.

Чтобы сделать это, вам нужно mmap(..., MAP_SHARED, ...) память, инициализировать мьютекс в этой памяти, затем fork.

...