目录
线程共享一个地址空间 ,把资源(代码和数据)化成若干份,供各个线程使用
- 线程的栈和上下文不是共享的
- 以前学习的进程是具有一个线程的进程
线程的优势:
- 创建和销毁一个线程比进程的代价小的多
- 与进程之间的切换相比,线程之间的切换需要操作系统做的工作要少很多(调度更快)
- 某个线程进行I/O等待时,可以去执行其他线程
线程的缺点:
- 编写难度更高
- 不能控制线程执行的先后顺序(例如:一个函数执行需要另一个函数的返回值)
- 某个线程出错误,被发送信号,信号是发给进程,进程会关闭那么所有线程都关闭;(线程出问题会影响其他线程)
1.线程的创建
成功返回0,失败返回退出码
#include<iostream>
#include<cstdio>
#include<pthread.h>
#include<unistd.h>
using namespace std;
void* thread_run(void* msg)
{
char* tmp=(char*)msg;
while(1)
{
printf("%s : %lu\n",tmp,pthread_self());//pthread_self:返回线程的id
sleep(1);
}
return NULL;
}
int main()
{
pthread_t id;
pthread_create(&id,NULL,thread_run,(void*)"I am thread");//创建线程
while(1)
{
printf("id: %lu\n",id);//%lu:32位无符号整形
printf("I am mian thread : %lu\n",pthread_self());
sleep(1);
}
return 0;
}
ps -aL:查看线程LWP(轻量级进程(Light Weight Process))
g++ -o $@ $^ -lpthread:编译要加pthread库
2.线程等待
2.1.pthread_join
成功返回0,失败返回退出码
#include<iostream>
#include<cstdio>
#include<pthread.h>
#include<unistd.h>
using namespace std;
void* thread_run(void* msg)
{
char* tmp=(char*)msg;
printf("%s : %lu\n",tmp,pthread_self());
sleep(3);
return (void*)520;//强转
}
int main()
{
pthread_t id;
pthread_create(&id,NULL,thread_run,(void*)"I am thread");
printf("id: %lu\n",id);
printf("I am mian thread : %lu\n",pthread_self());
void* status=NULL;
pthread_join(id,&status);
printf("status: %d\n",(long long)status);//void*64位下8个字节
return 0;
}
2.2.线程终止的方案
- return退出线程(1.main线程退出,则进程退出;2.其他线程退出,则退出对应线程)
- pthread__exit(1.main线程退出,则进程退出;2.其他线程退出,则退出对应线程);exit:退出进程
- pthread_cancel取消线程;进程取消的退出码:-1;
#include<iostream>
#include<cstdio>
#include<pthread.h>
#include<unistd.h>
using namespace std;
void* thread_run(void* msg)
{
char* tmp=(char*)msg;
printf("%s : %lu\n",tmp,pthread_self());
sleep(3);
return (void*)520;
}
int main()
{
pthread_t id;
pthread_create(&id,NULL,thread_run,(void*)"I am thread");
void* status=NULL;
pthread_cancel(id);//取消进程
pthread_join(id,&status);
printf("status: %d\n",(long long)status);
return 0;
}
3.线程分离
- 线程分离后,执行结束会自动释放
#include<iostream>
#include<cstdio>
#include<pthread.h>
#include<unistd.h>
using namespace std;
void* thread_run(void* msg)
{
pthread_detach(pthread_self());//线程分离
char* tmp=(char*)msg;
return (void*)520;
}
int main()
{
pthread_t id;
pthread_create(&id,NULL,thread_run,(void*)"I am thread");
void* status=NULL;
sleep(1);
int ret=pthread_join(id,&status);//线程等待
printf("ret: %d,status: %d\n",ret,(long long)status);
return 0;
}
线程分离后不能等待线程