Linux基础编程 消息队列 msgsnd
| [日期:2012-07-11] |
来源:Linux社区
作者:ghostyu |
[字体:大 中 小]
|
源文件3 thread.c 根据上一篇文章修改
-
-
-
-
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
- #include <sys/msg.h>
-
- #include "msg.h"
-
- #define __DEBUG
- #ifdef __DEBUG
- #define DBG(fmt,args...) fprintf(stdout, fmt, ##args)
- #else
- #define DBG(fmt,args...)
- #endif
- #define ERR(fmt,args...) fprintf(stderr, fmt, ##args)
-
- static int isThreadQuit = 0;
- int gQid;
- int gMyProcId = MSG_TYPE_MSG1;
-
-
-
-
-
-
-
- void DeviceWrite(char *str)
- {
-
- DBG("Device Write: %s\n",str);
-
- }
- void SetXxThreadQuit()
- {
-
- isThreadQuit = 1;
- }
- void *XxManageThread(void *arg)
- {
- char *cmd = (char*)arg;
- DBG("arg value=%s\n",cmd);
- static int i=0;
- while(isThreadQuit==0){
-
- MSG_BUF msg;
- memset(&msg,0,sizeof(MSG_BUF));
- msg.Des = MSG_TYPE_MSG1;
- msg.Src = gMyProcId;
- msg.cmd = i++;
-
-
-
-
-
- msgsnd(gQid,(void*)&msg,sizeof(MSG_BUF)-sizeof(long),0);
- DBG("msgsnd cmd = %d\n",msg.cmd);
- sleep(1);
-
- }
-
- pthread_exit(cmd);
-
- }
- void *XxManageThreadMutex(void *arg)
- {
- char *cmd = (char*)arg;
- DBG("arg value=%s\n",cmd);
- while(isThreadQuit==0){
-
- MSG_BUF msg;
- memset(&msg,0,sizeof(MSG_BUF));
-
-
-
-
- int ret = msgrcv(gQid,(void*)&msg,sizeof(MSG_BUF)-sizeof(long),gMyProcId,0);
- if(ret < 0){
- ERR("Receive msg fail!!\n");
- break;
- }
- DBG("msgrcv cmd = %d\n",msg.cmd);
- sleep(1);
-
- }
-
- pthread_exit(cmd);
-
- }
-
- int XxManageThreadInit()
- {
- pthread_t tManageThread;
- pthread_t tManageThreadMutex;
-
- char *any="any value";
- char *retn;
- int ret;
-
-
-
-
- ret = pthread_create(&tManageThread,NULL,XxManageThread,"1 thread");
- if(ret == -1){
-
- ERR("Ctreate Thread ERROR\n");
- return -1;
- }
-
- ret = pthread_create(&tManageThreadMutex,NULL,XxManageThreadMutex,"2 thread");
- if(ret == -1){
-
- ERR("Ctreate Thread ERROR\n");
- return -1;
- }
-
-
-
-
-
- pthread_detach(tManageThread);
- pthread_detach(tManageThreadMutex);
-
-
- return 0;
- }
-
- #define TEST_MAIN
- #ifdef TEST_MAIN
- int main()
- {
- printf("hello liuyu\n");
- int count=3;
-
-
- gQid = Msg_Init(MSG_KEY);
- if(XxManageThreadInit()==-1){
- exit(1);
- }
-
- while(count--){
- DBG("[0] main running\n");
- sleep(2);
- }
-
- SetXxThreadQuit();
-
- sleep(1);
-
-
- Msg_Kill(gQid);
- DBG("waitting thread exit...\n");
- return 0;
- }
- #endif

评论声明
- 尊重网上道德,遵守中华人民共和国的各项有关法律法规
- 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
- 本站管理人员有权保留或删除其管辖留言中的任意内容
- 本站有权在网站内转载或引用您的评论
- 参与本评论即表明您已经阅读并接受上述条款
|
|
|
|