进程间同步-互斥量

互斥量常用来做线程间同步,不过,我们可以恰当设置其属性实现进程间同步

互斥量类型为pthread_mutexattr_t,使用pthread_mutexattr_init函数来初始化,使用pthread_mutexattr_setpshared来设置pshared属性,进程锁属性设置为PTHREAD_PROCESS_SHARED

#include <stdio.h>
#include <sys/wait.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>


int main()
{
    pthread_mutexattr_t attr;
    pthread_mutex_t mutex;

    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
    pthread_mutex_init(&mutex, &attr);

    pid_t pid = fork();
    if (pid > 0)
    {
        pthread_mutex_lock(&mutex);
        printf("in parent process\n");
        sleep(2);
        pthread_mutex_unlock(&mutex);
        wait(NULL);
    }
    else if (pid == 0)
    {
        sleep(1);
        pthread_mutex_lock(&mutex);
        printf("in child process\n");
        pthread_mutex_unlock(&mutex);
        _exit(0);
    }

    pthread_mutexattr_destroy(&attr);
    pthread_mutex_destroy(&mutex);

    return 0;
}

  

posted @ 2019-01-21 16:12  二狗啸地  阅读(710)  评论(0编辑  收藏  举报