简单的消息队列

#include 
#include 
#include 
#include 
#include 
#include 

#define MAX_MESSAGE_SIZE 100

typedef struct {
    long mtype; // 消息类型
    char mtext[MAX_MESSAGE_SIZE]; // 消息数据
} Message;

typedef struct {
    pthread_t thread;
    int msqid;
} ThreadData;

void* producer(void *arg) {
    ThreadData *data = (ThreadData*)arg;
    int msqid = data->msqid;

    for (int i = 0; i < 10; i++) {
        Message message;
        message.mtype = 1; // 消息类型,这里使用 1 作为示例
        sprintf(message.mtext, "Message %d", i); // 消息数据,这里使用字符串作为示例

        if (msgsnd(msqid, &message, sizeof(message.mtext), 0) == -1) {
            perror("msgsnd");
            exit(EXIT_FAILURE);
        }

        printf("Producer: Sent message: %s\n", message.mtext);
    }

    pthread_exit(NULL);
}

void* consumer(void *arg) {
    ThreadData *data = (ThreadData*)arg;
    int msqid = data->msqid;

    for (int i = 0; i < 10; i++) {
        Message message;

        if (msgrcv(msqid, &message, sizeof(message.mtext), 1, 0) == -1) {
            perror("msgrcv");
            exit(EXIT_FAILURE);
        }

        printf("Consumer: Received message: %s\n", message.mtext);
    }

    pthread_exit(NULL);
}

int main() {
    key_t key;
    int msqid;
    ThreadData producerData, consumerData;

    // 生成一个唯一的 key
    if ((key = ftok(".", 'M')) == -1) {
        perror("ftok");
        exit(EXIT_FAILURE);
    }

    // 创建消息队列
    if ((msqid = msgget(key, IPC_CREAT | 0666)) == -1) {
        perror("msgget");
        exit(EXIT_FAILURE);
    }

    producerData.msqid = msqid;
    pthread_create(&producerData.thread, NULL, producer, (void*)&producerData);

    consumerData.msqid = msqid;
    pthread_create(&consumerData.thread, NULL, consumer, (void*)&consumerData);

    pthread_join(producerData.thread, NULL);
    pthread_join(consumerData.thread, NULL);

    // 删除消息队列
    if (msgctl(msqid, IPC_RMID, NULL) == -1) {
        perror("msgctl");
        exit(EXIT_FAILURE);
    }

    return 0;
}

你可能感兴趣的:(java,算法,linux)