#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
pthread_t pid_1,pid_2;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int msgid;
typedef struct{
long mtype;
int date;
}msg;
void *func2(void *arg)
{
int i = 1,j =1;
msg sendData;
pthread_detach(pthread_self());
while(1)
{
sleep(2);
sendData.mtype = i++;
sendData.date= j++;
if(( msgsnd(msgid,&sendData,sizeof(msg)-sizeof(sendData.mtype),0))<0)
{
perror("msgsnd:");
pthread_exit(NULL);
}else
{
pthread_mutex_lock(&mutex);
printf("send:mtype= %ld,data = %d\n",sendData.mtype,sendData.date);
pthread_mutex_unlock(&mutex);
}
}
}
void *func1(void *arg)
{
pthread_create(&pid_2,NULL,func2,NULL);
msg reData;
while(1)
{
if((msgrcv(msgid,&reData,sizeof(reData)-sizeof(reData.mtype),0,0))<0)
{
perror("msgrcv:");
pthread_exit(NULL);
}else{
pthread_mutex_lock(&mutex);
printf("recv:mtype= %ld,data = %d\n",reData.mtype,reData.date);
pthread_mutex_unlock(&mutex);
}
}
pthread_join(pid_2,NULL);
printf("func1--son exit \n");
}
int main(int argc, char *argv[])
{
if((msgid = msgget(3123,IPC_CREAT|0666))<0)
{
perror("msgget:");
return 0;
}
pthread_create(&pid_1,NULL,func1,NULL);
pthread_join(pid_1,NULL);
printf("main--son exit \n");
printf("father exit\n");
return 0;
}
标签:mtype,sendData,队列,间通信,int,线程,pthread,msg,include From: https://www.cnblogs.com/czy363/p/18574129