线程

什么是线程

  1. 线程是在进程内部运行的一个执行流
  2. linux下没有真正意义上的线程,是用进程模拟的
    在这里插入图片描述

优点

  1. 创建一个新线程的代价要比创建一个新进程的代价小
  2. 与进程间切换比,线程切换操作系统做的工作少
  3. 线程占用的资源少
  4. 能充分利用多处理器的可并行数量
  5. 在等待慢速I/O结束的同时,可以执行其他计算任务
  6. 计算密集型应用,为了能在多个处理器系统上运行,将计算分解到多个线程中实现
  7. I/O密集型应用,可以同时等待不同I/O的操作

缺点

  1. 性能损失
  2. 健壮性低
  3. 缺乏访问控制
  4. 编程难度高

进程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相同证明在同一进程中。

进程终止

  1. 线程将自己的入口函数运行完毕return退出
  2. void pthread_exit(void *retval); 退出调用线程
  3. void pthread_cancel(pthread_t tid); 取消一个指定线程

线程等待

已经退出的线程,其空间没有被释放,仍然在进程的地址空间内。
创建新的线程不会复用刚才退出线程的地址空间。
int pthread_join(pthread_t thread, void **retval);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值