Linux訊息佇列與執行緒例項理解
阿新 • • 發佈:2018-11-13
相較於程序,執行緒不僅擁有程序的併發性,相互獨立等特點,更有佔用資源較少,效率高等特點。
建立執行緒
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
其中thread為執行緒ID地址
attr 為屬性設定
start_routine為函式指標
arg為start_routine函式的引數
退出執行緒
void pthread_exit(void *retval);
其中retval
等待執行緒退出
int pthread_join(pthread_t thread, void **retval);
其中thread為執行緒id
retval為捕獲的執行緒退出後的引數
例項:通過訊息佇列月執行緒實現兩程序互相傳送訊息並列印
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
struct msgbuf
{
long mtype;
char mtex[40];
};
int msid;
struct msgbuf msre,mswr;
void * f(void * buf)
{
while(1)//子執行緒
{
bzero(msre.mtex,40);
if(msgrcv(msid,&msre,sizeof(msre),100,0)==-1)//從訊息佇列msid中,獲取型別(mtype)為100的資訊,放到msre中,未獲得則阻塞
{
perror("get massage fail");
exit(-1);
}
printf("massage : %s\n",msre.mtex);
if(strcmp(msre.mtex,"end")==0)
{
msgctl(msid,IPC_RMID,NULL);
exit(0);
}
printf("Please import massage or wait for massage:\n");
}
}
int main (void)
{
key_t key = ftok(".",123);
msid = msgget(key,IPC_CREAT|0666);
if(msid<0)
{
perror("get msgid fail");
return ;
}
mswr.mtype = 200;
char a[40] = {'\0'};
pthread_t id;
pthread_create(&id,NULL,f,NULL);
printf("Please import massage or wait for massage:\n");//建立執行緒
while(1)//主執行緒
{
bzero(mswr.mtex,40);
gets(a);
stpcpy(mswr.mtex,a);
if(msgsnd(msid,&mswr,strlen(mswr.mtex),0)==-1)//將mswr中的內容放到訊息佇列msid中放入大小為strlen,未傳送則阻塞
{
perror("send fail");
return 0;
}
if(strcmp(msre.mtex,"end")==0)
{
msgctl(msid,IPC_RMID,NULL);
exit(0);
}
printf("Please import massage or wait for massage:\n");
}
pthread_join(id,NULL);
}