linux进程间互斥锁和条件变量

Deadly 提交于 2020-02-19 00:12:16

  1. 设置进程间共享属性互斥锁和条件变量
  2. 将该互斥锁和条件变量放到共享内存中

public.h

#ifndef _PUBLIC_H
#define _PUBLIC_H

#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <sys/mman.h>
#include <sys/stat.h>        /* For mode constants */
#include <fcntl.h>           /* For O_* constants */

typedef struct interaction {
	int id;
	char name[8];
    pthread_cond_t cond;
    pthread_mutex_t mutex;
}Interaction;

extern Interaction* get_interaction(const char *filename);

#endif // _PUBLIC_H

interaction.c

#include "public.h"

Interaction* get_interaction(const char *filename)
{
    Interaction *share_mem;
	int len = sizeof(Interaction);

    int fd = shm_open(filename, O_RDWR|O_CREAT|O_EXCL, 0777);
    if (fd > 0) {
        /**< 设置共享内存长度 */
        ftruncate(fd, len);
        share_mem = (Interaction *)mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

        pthread_condattr_t cond_attr;
        pthread_condattr_init(&cond_attr);
        pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED);
        pthread_cond_init(&share_mem->cond, &cond_attr);


        pthread_mutexattr_t mutex_attr;
        pthread_mutexattr_init(&mutex_attr);
        pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
        pthread_mutex_init(&share_mem->mutex, &mutex_attr);

		printf("mmap Interaction object(%p) ok\n", share_mem);
    } else {
		perror("ready");
        fd = shm_open(filename, O_RDWR, 0777);
        /**< 其他进程已经初始化过了,这里不要再初始化 */
        share_mem = (Interaction *)mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
		printf("get Interaction object(%p) ok\n", share_mem);
    }
    close(fd);
//    shm_unlink("/test_share_mem"); 

    return share_mem;
}

signal.c

#include "public.h"

int main()
{
	Interaction *share_mem = get_interaction("test_share_mem");
    
    while (1) {
        char buf[1024];
        fgets(buf, sizeof(buf), stdin);
		strncpy(share_mem->name, buf, 7);
		printf("send condtion signal\n");
        pthread_cond_signal(&share_mem->cond);
    }
}

wait.c

#include "public.h"

int main()
{
	Interaction *share_mem = get_interaction("test_share_mem");
	pthread_cond_t *cond = &share_mem->cond;
	pthread_mutex_t *mutex = &share_mem->mutex;

    while (1) {
        pthread_mutex_lock(mutex);  
        pthread_cond_wait(cond, mutex);  
        pthread_mutex_unlock(mutex);

        printf("get Interaction: %s\n", share_mem->name);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!