码迷,mamicode.com
首页 > 系统相关 > 详细

pthread mutex 进程间互斥锁

时间:2019-04-28 18:42:05      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:第一个   fail   RoCE   red   初始化   style   互斥锁   共享   init   

 

共享标志 定义 名称 描述
0 PTHREAD_PROCESS_PRIVATE 进程内互斥锁 仅可当前进程内共享
1 PTHREAD_PROCESS_SHARED 进程间互斥锁 多个进程间共享

第一个程序代码

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>

int main(int argc, char* argv[])
{
    char mmap_file_path[512] = { 0 };
    getcwd(mmap_file_path, sizeof(mmap_file_path));
    strcat(mmap_file_path, "/pthread_shared");

    int fd = open(mmap_file_path, O_RDWR | O_CREAT, 0744);
    if (0 < fd)
    {
        //重置文件大小
        ftruncate(fd, sizeof(pthread_mutex_t));

        pthread_mutex_t* mutex_ptr = (pthread_mutex_t*)mmap(0, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

        close(fd);

        //初始化锁对象
        pthread_mutexattr_t attr;
        pthread_mutexattr_init(&attr);
        pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
        pthread_mutex_init(mutex_ptr, &attr);int lock_ret = pthread_mutex_lock(mutex_ptr);

        if (0 == lock_ret)
        {
            printf("lock successed\n");
            usleep(10 * 1000 * 1000);
            pthread_mutex_unlock(mutex_ptr);
        }
        else
        {
            printf("lock failed: %d\n", lock_ret);
        }
    }
    else
    {
        printf("open err\n");
    }

    return 0;
}

第二个程序代码,特殊的在获取锁对象后不需要初始化,因为在第一个进程内已经初始化了

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

int main(int argc, char* argv[])
{
    char mmap_file_path[512] = { 0 };
    getcwd(mmap_file_path, sizeof(mmap_file_path));
    strcat(mmap_file_path, "/pthread_shared");

    int fd = open(mmap_file_path, O_RDWR | O_CREAT, 0744);
    if (0 < fd)
    {
        pthread_mutex_t* mutex_ptr = (pthread_mutex_t*)mmap(0, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

        close(fd);int lock_ret = pthread_mutex_lock(mutex_ptr);

        if (0 == lock_ret)
        {
            printf("lock successed\n");
            usleep(10 * 1000 * 1000);

            pthread_mutex_unlock(mutex_ptr);
        }
        else
        {
            printf("lock failed: %d\n", lock_ret);
        }
    }
    else
    {
        printf("open err\n");
    }

    return 0;
}

 

pthread mutex 进程间互斥锁

标签:第一个   fail   RoCE   red   初始化   style   互斥锁   共享   init   

原文地址:https://www.cnblogs.com/tianrks/p/10785577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!