#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
 
int msgid;
pthread_t pid_1,pid_2;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

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;
}

 

posted on 2024-11-28 13:42  轩~邈  阅读(38)  评论(0)    收藏  举报