
用两个消息对列实现线程消息队列双向通信
发布日期: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; }
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年04月28日 07时03分44秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
万倍币传说不再,价值回归
2021-05-10
这可能是后浪们逆袭的唯一机会
2021-05-10
观点 | COMP的流动性挖矿并非万能解药
2021-05-10
尽管DeFi项目数量下降,但总价值却仍在不断攀升
2021-05-10
Bakkt完成1.82亿美元首轮融资,这家交易所凭什么这么牛?
2021-05-10
每天维护费700多万美元!比特币当之无愧是“最安全区块链”
2021-05-10
看明白这两种情况,才敢说自己懂跨链! | 喵懂区块链24期
2021-05-10
6大亮点抢先看!Facebook加密货币项目Libra白皮书解读
2021-05-10
比特币回调至6000美元?分析师表示“很有可能”
2021-05-10
数字印钞界迎来重磅精英机构,普通人还有翻身机会吗? | 加密货币与阶层穿越...
2021-05-10
Java初识和开发环境搭建
2021-05-10
Wordpress主题Git后台清净模式设置
2021-05-10
张一鸣:创业7年,我经历的5件事
2021-05-10
SQL基础语法
2021-05-10
SQL 已死,但 SQL 将永存
2021-05-10
Python3 日期和时间
2021-05-10
JavaScript实现表格排序
2021-05-10
vue散碎知识点学习
2021-05-10
周报二
2021-05-10
git拉取远程指定分支代码
2021-05-10