一、消息队列
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <pthread.h>
struct msgbuf{
long mtype;
char mtext[50];
};
void *routine1(void *arg)
{
struct msgbuf buf;
int msgid = (int)arg;
int ret;
while(1)
{
bzero(&buf,sizeof(buf));
ret = msgrcv(msgid,&buf,sizeof(buf),30,0);
if(ret == -1)
{
printf("msgrcv error!\n");
}
printf("buf.mtext = %s",buf.mtext);
sleep(1);
}
pthread_exit(NULL);
}
void *routine2(void *arg)
{
struct msgbuf buf;
int msgid = (int)arg;
int ret;
while(1)
{
bzero(&buf,sizeof(buf));
buf.mtype = 30;
fgets(buf.mtext,sizeof(buf.mtext),stdin);
msgsnd(msgid,&buf,strlen(buf.mtext),0);
}
}
int main()
{
key_t key;
int msgid;
key = ftok(".",10);
msgid = msgget(key,IPC_CREAT | 0666);
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,routine1,(void *)msgid);
pthread_create(&tid2,NULL,routine2,(void *)msgid);
pause();
}
二、共享内存
共享内存中被映射的空间属于临界资源所以要上锁
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <pthread.h>
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void *Jack_fun(void *arg)
{
char *p = (char *)arg;
while(1)
{
pthread_mutex_lock(&m);
fgets(p,8192,stdin);
pthread_mutex_unlock(&m);
if(strncmp(p,"quit",4) == 0)
{
break;
}
usleep(100000);
}
pthread_exit(NULL);
}
void *Rose_fun(void *arg)
{
usleep(50000);
char *p = (char *)arg;
while(1)
{
pthread_mutex_lock(&m);
printf("from shm:%s",p);
pthread_mutex_unlock(&m);
if(strncmp(p,"quit",4) == 0)
{
break;
}
usleep(130000);
}
pthread_exit(NULL);
}
int main()
{
key_t key;
int shmid;
key = ftok(".",10);
shmid = shmget(key,8192,IPC_CREAT|0666);
char *p = (char *)shmat(shmid,NULL,0);
pthread_t Jack,Rose;
pthread_create(&Jack,NULL,Jack_fun,(void *)p);
pthread_create(&Rose,NULL,Rose_fun,(void *)p);
pthread_join(Jack,NULL);
pthread_join(Rose,NULL);
return 0;
}
|