学习之路--pthread多线程的操作
我之前不怎么使用多线程,直到发现将所有的代码杂糅在一个进程中,会特别的卡,但其实CPU的使用率并不是很高,所以采用多任务处理,并发执行的操作就能优化整个程序。
所以,进入主题--------pthread。
Linux中实现多线程的操作
linux系统中包含pthread库,实现多线程比较简单,下面就是一个实例:
主线程负责发送数据
子线程实现接收数据
包含头文件:
#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> //包含thread 库
新建一个消息的结构体
struct msgbuf
{
long mtype; // 消息的类型
char mtex[40]; // 消息的大小
};
//定义两个结构体,一个是负责发送消息的结构体,另一个是负责接收消息的结构体
struct msgbuf msre, mswr;
//结束消息通信的变量
char end[5] = { "end\n" };
/////////////////////////////////////////////////////////////////
//子线程:接收数据
/////////////////////////////////////////////////////////////////
void *recv(void *buf)
{
while (1) //son thread
{
key_t key = ftok(".", 123); //key_t is similar with int or long type , ftok get IPC communication id,the frist parameter is file path,the second is behind 8bit num of id.
sleep(1);
int msid = msgget(key, IPC_CREAT | 0666);//(read|write)
bzero(msre.mtex, 40);//msre full 0
if (msgrcv(msid, (void *)&msre, sizeof(msre), 100, 0) == -1)//get mtype in the msid=100 of mssage queue,and putit in msre, if msid don't geted , will blocking
{
perror("get message fail");
exit(-1);
}
printf("message :%s\n", msre.mtex);
if (strcmp(msre.mtex, end) == 0)
{
msgctl(msid, IPC_RMID, NULL); // message end
printf("pthread end!\n");
exit(0);
}
printf("Please import message :\n");
}
}//主要负责接收主线程发送过来的数据,注意红色的100,这是消息的类型,要求与主线程的消息类型保持一致
////////////////////////////////////////////////////////////////////////////
//主线程:负责发送消息
///////////////////////////////////////////////////////////////////////////
int main(void)
{
key_t key = ftok(".", 123); //key_t is similar with int or long type , ftok get IPC communication id,the frist parameter is file path,the second is behind 8bit num of id.
int msid = msgget(key, IPC_CREAT | 0666);// (read|wirte)
if (msid < 0)
{
perror("get msgid fail");
return;
}
system("ipcs -q"); // show message
mswr.mtype = 100; // must same whit msre
char a[40] = { '\0' };
pthread_t id;
pthread_create(&id, NULL, recv, NULL); // new a thread recv
printf("Please import message:\n");//
while (1)// main thread
{
bzero(mswr.mtex, 40);
fgets(mswr.mtex, 40, stdin);
sleep(1);
if (msgsnd(msid, (void *)&mswr, strlen(mswr.mtex), 0) == -1)//put mswr in msid of message queue ,and size is strlen,IPC_NOWAIT is no blocking.
{
perror("send fail");
return 0;
}
printf("string :%s", mswr.mtex);
if (strcmp(mswr.mtex, end) == 0)
{
printf("main pthread end!\n");
msgctl(msid, IPC_RMID, NULL);
exit(0);
}
}
pthread_join(id, NULL);
}
实现效果:

浙公网安备 33010602011771号