文章目录
一、消息队列
1.消息队列
消息队列:传送有格式的消息流
多进程网络交叉通信,实现大规模数据通信
使用内核中的链表(实现机制)
2.posix的消息队列和系统V消息队列的区别
消息队列是随内核持续的
二、线程
1.什么是线程
线程是进程的一个实体,它是程序运行的最小单位
(线程在进程之间时可以相互通信,通过全局变量)
2、为什么要学习线程
1)线程是进程的一个实体,它是程序运行的最小单位,它比进程要消耗更少的资源
2)能共享地址空间(进程)(堆栈:程序栈)
3、线程由哪些组成
1)指令指针(指向当前被执行的命令)
2)一个栈(函数栈)
3)寄存器的集合(状态寄存器:一部分正在运行中的处理器状态)
4)一个私有的数据区
4、线程的特点
1、线程切换的开销很低(实质是函数切换)
2、线程的通信机制简单(共用的地址空间,全局变量通信)
5、线程并不是操作系统中内核提供的而是由线程库来提供libpthread.a/.so(调用)
三、创建线程
1、创建线程
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
pthread_t *thread:指向线程的指针
const pthread_attr_t *attr:创建线程是的属性:NULL无属性创建
void *(*start_routine) (void *):线程运行的实体函数指针
void *arg:线程参数
注意:线程是进程的一个实体,一旦主进程运行结束,线程就会被回收
创建两个次线程,两个次线程分别的向同一个文件写“hello”“world\n” “hhhhhwwwww\n”
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
void *test(void *arg)
{
printf("subpthread\n");
}
int main()
{
pthread_t id;
//创建一个子线程
int ret = pthread_create(&id, NULL, test,NULL);
if(0 != ret)
{
perror("pthread_create error!");
exit(0);
}
// while(1);
pause();//挂起
return 0;
}
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
void *test(void *arg)
{
int *num = (int *)arg;
printf("subpthread:%d\n",*num);
sleep(1);
}
int main()
{
int i=5;
pthread_t id;
int ret = pthread_create(&id, NULL