使用 Mutex 實現進程間同步



我們知道 Mutex 互斥量是可以用在線程間同步的,線程之間共享進程的數據,mutex 就可以直接引用。而進程有自己獨立的內存空間,要怎樣將它應用在進程間同步呢?為了達到這一目的,可以在 pthread_mutex_init 初始化之前,修改其屬性為進程間共享,並將其映射到共享內存中即可。


使用到的API:

pthread_mutexattr_t mattr 類型:		用於定義互斥量的屬性

pthread_mutexattr_init 函數:			初始化一個mutex屬性對象

pthread_mutexattr_destroy 函數:		銷毀 mutex 屬性對象

pthread_mutexattr_setpshared 函數:	修改 mutex 屬性。

pthread_mutexattr_setpshared 函數使用:

int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared);

pshared 參數:它有以下兩個取值:

線程鎖:PTHREAD_PROCESS_PRIVATE (mutex的默認屬性即為線程鎖,進程間私有)

進程鎖:PTHREAD_PROCESS_SHARED

要想實現進程間同步,需要將 mutex 的屬性改為 PTHREAD_PROCESS_SHARED。

應用實例:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <string.h>

/* 定義 mutex */
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;

int main()
{
        int shm_id = 0;
        int i = 0;
        pid_t pid;
        pthread_mutex_t *m_mutex;

        /* mutex attr 初始化 */
        pthread_mutexattr_init(&mutexattr);
        /* 修改屬性 */
        pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED);
        /* mutex 初始化 */
        pthread_mutex_init(&mutex, &mutexattr);

        /* 申請共享內存 */
        shm_id = shmget((key_t)1004, sizeof(mutex), IPC_CREAT | 0600);
        /* 映射共享內存到進程地址空間 */
        m_mutex = (pthread_mutex_t*)shmat(shm_id, 0, 0);
        memcpy(m_mutex, &mutex, sizeof(mutex));

        pid = fork();

        if(pid == 0){
                pthread_mutex_lock(m_mutex);
                for(; i<3; i++){
                        pthread_mutex_lock(m_mutex);
                        puts("This is the child process!");
                }
        }else if(pid > 0){
                for(; i<3; i++){
                    sleep(1);
                    pthread_mutex_unlock(m_mutex);
                    puts("This is the parent process!");
        }

        /* 回收子進程資源 */
                wait(NULL); 
        }

        /* 銷毀 mutex */
        pthread_mutexattr_destroy(&mutexattr);
        pthread_mutex_destroy(&mutex);

        return 0;
}

運行結果:

[root@localhost 24th_processSync]# ./a.out 
This is the parent process!
This is the child process!
This is the parent process!
This is the child process!
This is the parent process!
This is the child process!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM