什么是线程
- 线程是在进程内部运行的一个执行流
- linux下没有真正意义上的线程,是用进程模拟的
优点
- 创建一个新线程的代价要比创建一个新进程的代价小
- 与进程间切换比,线程切换操作系统做的工作少
- 线程占用的资源少
- 能充分利用多处理器的可并行数量
- 在等待慢速I/O结束的同时,可以执行其他计算任务
- 计算密集型应用,为了能在多个处理器系统上运行,将计算分解到多个线程中实现
- I/O密集型应用,可以同时等待不同I/O的操作
缺点
- 性能损失
- 健壮性低
- 缺乏访问控制
- 编程难度高
进程VS线程
1. 进程是资源分配的基本单位
2. 线程是调度的基本单位
3. 线程共享进程资源,但是拥有独立栈结构,独立硬件上下文(因为线程是会被调度的)
4. 文件描述符共享
进程创建
1 #include<iostream>
2 #include<string>
3 #include<unistd.h>
4 #include<sys/types.h>
5 #include<pthread.h>
7 using namespace std;
8
9 void *thread_routine(void* arg)
10 {
11 string str = (char*)arg;
12 while(1)
13 {
14 cout << str << "run"<< "pid: "<< getpid()<<endl;
15 sleep(1);
16 }
17 }
18 int main()
19 {
20 pthread_t tid;
21 pthread_create(&tid, NULL, thread_routine, (void*)"thread 1");
22 pthread_create(&tid, NULL, thread_routine, (void*)"thread 2");
23 pthread_create(&tid, NULL, thread_routine, (void*)"thread 3");
24 pthread_create(&tid, NULL, thread_routine, (void*)"thread 4");
25 while(1)
26 {
27 cout << "main thread run" << "pid: " <<getpid()<<endl;
28 sleep(2);
29 }
30 return 0;
31 }
1,2,3,4和主线程都在运行,但是PID相同证明在同一进程中。
进程终止
- 线程将自己的入口函数运行完毕return退出
- void pthread_exit(void *retval); 退出调用线程
- void pthread_cancel(pthread_t tid); 取消一个指定线程
线程等待
已经退出的线程,其空间没有被释放,仍然在进程的地址空间内。
创建新的线程不会复用刚才退出线程的地址空间。
int pthread_join(pthread_t thread, void **retval);