用两个消息对列实现线程消息队列双向通信
发布日期:2021-05-10 05:07:22 浏览次数:19 分类:精选文章

本文共 2248 字,大约阅读时间需要 7 分钟。

���������������

������������ msgid1��� ������1������ TYPE_B ���������������������2��������� TYPE_A���

������������ msgid2��� ������2������ TYPE_A ���������������������1��������� TYPE_B���

#include 
#include
#include
#include
#include
#include
#include
#include
#include
#define TYPE_A 1 // ������������ #define TYPE_B 2 // ������������ int msgid1 = -1; int msgid2 = -1; typedef struct { long mtype; // ��������������������������� 0 char mtext[1024]; // ��������������������������������������� } msgbuf; int thread1(void) { int ret; while (1) { msgbuf mbuf; memset(&mbuf, 0, sizeof(mbuf)); mbuf.mtype = TYPE_B; // ������������������ strcpy(mbuf.mtext, "hello "); ret = msgsnd(msgid1, &mbuf, sizeof(mbuf.mtext), 0); if (ret < 0) { perror("msgsnd"); return -1; } memset(&mbuf, 0, sizeof(mbuf)); ret = msgrcv(msgid2, &mbuf, sizeof(mbuf.mtext), TYPE_A, 0); if (ret < 0) { perror("msgrcv"); return -1; } printf("thread2 send %s\n", mbuf.mtext); usleep(10000); } } int thread2(void) { int ret; while (1) { msgbuf mbuf; memset(&mbuf, 0, sizeof(mbuf)); mbuf.mtype = TYPE_A; // ������������������ strcpy(mbuf.mtext, "hi"); ret = msgsnd(msgid2, &mbuf, sizeof(mbuf.mtext), 0); if (ret < 0) { perror("msgsnd"); return -1; } memset(&mbuf, 0, sizeof(mbuf)); ret = msgrcv(msgid1, &mbuf, sizeof(mbuf.mtext), TYPE_B, 0); if (ret < 0) { perror("msgrcv"); return -1; } printf("thread1 send %s\n", mbuf.mtext); usleep(10000); } } int main(void) { int ret; pthread_t tid1, tid2; msgid1 = msgget(0x7777, IPC_CREAT | 0777); msgid2 = msgget(0x8888, IPC_CREAT | 0777); if (msgid1 < 0) { printf("create msgid1 queue fail\n"); return -1; } if (msgid2 < 0) { printf("create msgid2 queue fail\n"); return -1; } ret = pthread_create(&tid1, NULL, (void *)thread1, NULL); if (ret != 0) { printf("Create thread1 error!\n"); exit(1); } ret = pthread_create(&tid2, NULL, (void *)thread2, NULL); if (ret != 0) { printf("Create thread2 error!\n"); exit(1); } pthread_join(tid1, NULL); pthread_join(tid2, NULL); ret = msgctl(msgid1, IPC_RMID, NULL); if (ret < 0) { perror("msgid1 msgctl"); return -1; } ret = msgctl(msgid2, IPC_RMID, NULL); if (ret < 0) { perror("msgid2 msgctl"); return -1; } return 0; }
上一篇:Linux socket can调试测试记录
下一篇:消息队列用于双向进程通信

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年04月28日 07时03分44秒