您的位置:首页 > 其它

信息队列使用举例

2015-02-01 22:50 337 查看
/*thread.c*/  

#include <stdio.h>  

#include <pthread.h>  

#include <stdlib.h>

#include <unistd.h>

#include <mqueue.h>

#include <string.h>

#define QUEUE_NAME "/msgQtest"

#define MAX_SIZE (255)

#define ERROR (-1)

#define OK (0)

/*线程一*/  /*receiver*/

void thread_1(void *args){

char buffer[MAX_SIZE + 1];
mqd_t *mqd;
mqd = ((mqd_t**) args)[0];
int ret;

do{
ret = mq_receive(*mqd, buffer, MAX_SIZE, NULL);
if (ret != OK){
fprintf(stderr, "%s:%d: ", __FUN__, __LINE__);
pthread_exit(0);
}
printf("receiverd msg = %d/n",(int)buffer);
sleep (400);
}while((int)buffer != 10);
pthread_exit(0);

}  

  

/*线程二*/   /*sender*/

void thread_2(void *args)

{  

char buffer[MAX_SIZE + 1];

    mqd_t *mqd;
int tmpValue = 0;
int ret;

mqd = ((mqd_t**) args)[0];
while(tmpValue != 20){

sprintf(buffer,"%d",tmpValue++);
ret = mq_send(*mqd, buffer, MAX_SIZE, (int)NULL);
if (ret != OK){
fprintf(stderr, "%s:%d: ", __func__, __LINE__);
pthread_exit(0);
}

}
pthread_exit(0);

}  

  

int main(int argc,char *argv[]){  

    
pthread_t id_1,id_2;
struct mq_attr attr;
mqd_t mqd = (mqd_t)NULL;

    int i,ret; 
void *arg[1] = {&mqd};

/* initialize the queue attributes */

    attr.mq_flags = 0;

    attr.mq_maxmsg = 10;

    attr.mq_msgsize = MAX_SIZE;

    attr.mq_curmsgs = 0;

mq_unlink(QUEUE_NAME);
mq_close(mqd);
mqd = mq_open(QUEUE_NAME,O_RDWR|O_NONBLOCK|O_CREAT|O_EXCL,0644,&attr);
if ( mqd != 0 ){
fprintf(stderr, "%s:%d: ", __func__, __LINE__);
return ERROR;
}

/*创建线程一*/  

    ret=pthread_create(&id_1,NULL,(void  *) thread_1,arg);  

    if( ret != 0 )  

    {  

        printf("Create pthread error!\n");  

    return ERROR;  

    }  

/*创建线程二*/  

    ret = pthread_create(&id_2,NULL,(void  *) thread_2,arg);  

    if( ret != 0 )  

    {  

        printf("Create pthread error!\n");  

    return ERROR;  

    }  

/*等待线程结束*/  

    pthread_join(id_1,NULL);  

    pthread_join(id_2,NULL);  

mq_close(mqd);
mq_unlink(QUEUE_NAME);

    return OK;  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: