首页 > 解决方案 > 发送和接收

问题描述

我有一个任务,我必须创建多个队列。目前我被卡住了,因为我不明白如何将消息发送到特定队列以及如何将输入的消息发送/接收到该特定队列。这是我写的代码:

typedef struct _node {
    const char *message;
    struct _node *next;
} node_t;

标签: cpointers

解决方案


我认为这段代码会产生预期的行为:

typedef struct msg_queue_node {
    char * message;
    struct msg_queue_node * next;
} msg_queue_node_t;


typedef struct msg_queue {
    msg_queue_node_t * head, * tail;
} msg_queue_t;


int main(void)
{
    int i, id;      // indentifies the message queue in the array
    msg_queue_t * msg_queues = malloc(NUM_QUEUES * sizeof(msg_queue_t*));

    for (i = 0; i < NUM_QUEUES; i++)
        msg_queues[i] = createQ();

    // ...

    while ( /*condition*/ ) {

        scanf("%c %d", choice, id);

        switch (choice) {
            case '4':
                printf("\nSending a message\nEnter message to send:");
                scanf("%s", msg);
                sendMessage(msg_queues[id-1], msg);
                break;
            case '5':
                printf("\nReceiving a message\n");
                printf("Message received: %s\n", receiveMessage(msg_queues[id-1]));
                break; 
        }
    }

    // ...
}

msg_queues大小为 的数组在哪里NUM_QUEUES

在我的解决方案中,我们希望用户输入他希望发送/接收消息的队列的标识符。我假设每个队列的标识符对应于它在数组中的索引+1,即标识符是1,...,NUM_QUEUES。


推荐阅读