首页 > 解决方案 > 生产者/消费者 - 消费者没有收到信号(无休止地等待)

问题描述

我正在与 IPC 合作;基本上有一个主程序,它启动 1,..,n 个进程。他们可以互相发送消息。共享内存有 256 个插槽来存储所有消息,内部每个进程当时只能存储 16 条消息(来自 256 条可用消息)。每个创建的进程在共享内存中都有一个信号量 full = 0,empty = 16

**Shared memory**

typedef struct
{
    pid_t pid;
    sem_t mutex;
    sem_t empty;
    sem_t full;
    int slots[OSMP_MAX_MSG_PROC];//16 slots
    int count;
    int proc_msg_head;
    int proc_msg_tail;
} PROC;

typedef struct
{
    char msg[OSMP_MAX_PAYLOAD_LENGTH]; //1024
    OSMP_Datatype typ;
    size_t len;
    int sender;
    int receiver;
} MSG;

typedef struct
{
    int p_count;
    size_t size;
    sem_t mutex;
    sem_t empty;
    int head;
    int tail;
    MSG slots[OSMP_MAX_SLOTS];
    char free_slots[OSMP_MAX_SLOTS]; //256
    PROC proc[1];
} * SHM_PTR;

我发消息:

    sem_wait(&shm->proc[dest].empty); // if not slots available wait

    int index_to_write = -1;
    if (buf == NULL)
        return OSMP_ERROR;
    if (dest > shm->p_count)
        return OSMP_ERROR;

    size_t length_msg = (size_t)count * OSMP_sizeOf(datatype);
    if (length_msg > OSMP_MAX_PAYLOAD_LENGTH)
    {
        perror("Length of data exceeded on Send");
        return OSMP_ERROR;
    }

    index_to_write = get_slot(); // get a free slot from shared mem
    memcpy(shm->slots[index_to_write].msg, buf, length_msg); //copy msg on shared mem
    shm->slots[index_to_write].len = length_msg;
    shm->slots[index_to_write].typ = datatype;
    shm->slots[index_to_write].sender = rank;
    shm->slots[index_to_write].receiver = dest;

   
    sem_wait(&shm->proc[dest].mutex);
     //put the message on internal inbox of the destination process
    sem_post(&shm->proc[dest].mutex);
 
    sem_post(&shm->proc[dest].full); //notify that there is a new msg

使用sem_post(&shm->proc[dest].full); 是应该递增的 proc[dest].full 的信号量。

但是当我尝试用sem_wait(&shm->proc[rank].full);接收它时 它没有得到完整信号量的信号

    int index_to_read = -1;
    if (buf == NULL)
        return OSMP_ERROR;

    size_t leng_msg = (size_t)count * OSMP_sizeOf(datatype);

    if (leng_msg > OSMP_MAX_PAYLOAD_LENGTH)
    {
        perror("Length of data exceeded on Recv");
        return OSMP_ERROR;
    }
    

    sem_wait(&shm->proc[rank].full); -------Here waits endless------


    sem_wait(&shm->proc[rank].mutex); //rank is the id of the process in the system
    index_to_read = shm->proc[rank].proc_msg_tail;
    shm->proc[rank].proc_msg_tail = (shm->proc[rank].proc_msg_tail + 1 % OSMP_MAX_MSG_PROC;
    sem_post(&shm->proc[rank].mutex);

    memcpy(buf, &shm->slots[index_to_read], leng_msg);
    *len = (int)leng_msg;
    *source = shm->slots[index_to_read].sender;
    sem_post(&shm->empty);

    return OSMP_SUCCESS;

有谁知道,为什么全信号量没有收到信号?

标签: cipcsemaphoreshared-memory

解决方案


推荐阅读