一.概念
1.线程是在进程内部运行的一种执行流,线程在进程的地址空间中运行
2.linux下的进程是只有一个线程的进程,
linux下的线程是用进程模拟出来的(并没有真正意义上的线程)。
3.linux下的线程叫轻量级进程。
4.创建一个线程只需要创建一个pcb即可。
5.进程与线程的区别:
- 进程是分配系统资源的基本单位。
- 调度的进本单位是线程
6.线程的私有(最重要的两点)
- 每个线程在运行的时候都会生成自己的临时变量,故每个线程都会有自己的栈内存,在每次运行结束后销毁自己的栈内存。
- 线程私有线程的上下文;作用是当被切换回来时或者再次调度的时候,继续使用自己的上下文。
7.进程的关键操作:创建 销毁 等待
8.等待的作用是为了解决出现类似于僵尸进程状态的线程。
二.用代码实现线程:
1.实现线程
所用函数:
返回值:成功返回零,出错返回错误码。
代码:
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>
void* start_routine(void*arg)
{
while(1)
{
pthread_t tid=pthread_self();
pid_t pid=getpid();
printf("I am a new pthread:tid:%lu pid:%d\n",tid,pid);
sleep(1);
}
}
int main()
{
pthread_t id=pthread_create(&id,NULL,*start_routine, NULL);
if(id!=0)
{
printf("%d:%s\n",id,strerror(id));
}
while(1)
{
pthread_t tid=pthread_self();
pid_t pid=getpid();
printf("I am a mian pthread:tid:%lu pid:%d\n ",tid,pid);
sleep(1);
}
return 0;
}
运行结果:
3.等待进程:
所用函数
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>
void* start_routine(void*arg)
{
int count=5;
while(count)
{
pthread_t tid=pthread_self();
pid_t pid=getpid();
printf("I am a new pthread:tid:%lu pid:%d\n",tid,pid);
count--;
sleep(1);
// pthread_exit(void*(123))
}
return 0;
}
int main()
{
pthread_t id;
void* val=NULL;
if(pthread_create(&id,NULL,*start_routine, NULL)!=0)
{
printf("%d:%s\n",id,strerror(id));
}
pthread_t tid=pthread_self();
pid_t pid=getpid();
int ret=pthread_join(id,&val);
printf("I am a mian pthread:tid:%lu pid:%d\n ",tid,pid);
printf("new pthread was died.main pthread will die:%d\n",(int)val);
return 0;
}
运行结果:
主线程在等待新线程运行结束后才退出。
4.线程取消函数
5.线程退出函数
6.线程退出的方法:
-从主函数中直接return;
-使用线程取消函数,(主要是让一个线程去取消其他的线程的,取消成功返回-1值)。
-使用线程退出函数。(在任意位置exit)。
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>
void* start_routine(void*arg)
{
int count=5;
while(count)
{
pthread_t tid=pthread_self();
pid_t pid=getpid();
printf("I am a new pthread:tid:%lu pid:%d\n",tid,pid);
count--;
sleep(1);
pthread_exit((void*)(123));
}
}
int main()
{
pthread_t id;
void* val=NULL;
if(pthread_create(&id,NULL,*start_routine, NULL)!=0)
{
printf("%d:%s\n",id,strerror(id));
}
pthread_t tid=pthread_self();
pid_t pid=getpid();
int ret=pthread_join(id,&val);
printf("I am a mian pthread:tid:%lu pid:%d\n ",tid,pid);
printf("new pthread was died.main pthread will die:%d\n",(int)val);
return 0;
}
运行结果: