运行结果如下:
文章插图
线程在创建过程中不会阻塞 , 主进程会立刻执行 , 那么存在一个问题 , 主进程如果执行完毕 , 那么所有线程都将被释放 , 就可能出现线程还未调度的问题 。(后面会解决)
线程和进程有区别 , 父子进程执行的代码段是一样的 , 但是线程被创建之后执行的是线程处理函数 。
再介绍一个函数:
就像每个进程都有一个进程号一样 , 每个线程也有一个线程号 。进程号再整个系统中是唯一的 , 但是线程号不同 , 线程号只在它所属的进程环境中有效 。
进程号用pid_t数据类型表示 , 是一个非负整数 。线程号则用pthread_t数据类型来表示 , Linux使用无符号长整型数表示 。
实例1: 创建一个线程 , 观察代码运行效果和函数用法
pthread_t pthread_self(void);功能:获取线程号参数:无返回值:调用线程的线程ID#include <stdio.h>#include <pthread.h>#include <unistd.h>void* pthreadrun(void* arg){ char* name = (char*)arg; while (1){printf("%s is running...\n", name);sleep(1); }}int main(){ pthread_t pthread; // 创建新线程 pthread_create(&pthread, NULL, pthreadrun, (void*)"new thread"); while (1){printf("main thread is running...\n");sleep(1); } return 0;}运行结果如下:
文章插图
实例2: 创建4个线程 , 然后打印出各自的pid和线程id
#include <stdio.h>#include <pthread.h>#include <unistd.h>void* pthreadrun(void* arg){ long id = (long)arg; while (1){ printf("threaad %ld is running, pid is %d, thread id is %p\n", id, getpid(), pthread_self()); sleep(1); }}int main(){ pthread_t pthread[5]; int i = 0; for (; i < 5; ++i) { // 创建新线程 pthread_create(pthread+i, NULL, pthreadrun, (void*)i); } while (1){ printf("main thread is running, pid is %d, thread id is %p\n", getpid(), pthread_self()); sleep(1); } return 0;}运行结果如下:
文章插图
可以看到六个线程的PID是一样的 , 同属于一个进程 , 但是它们还有一个表示 , LWP(light wighted process) , 轻量级进程的ID 。下面详细介绍 。
进程ID和线程ID
- 在Linux下 , 线程是由Native POSIX Thread Library 实现的 , 在这种实现下 , 线程又被称为轻量级进程(LWP) 。在用户态的每个进程 , 内核中都有一个与之对应的调度实体(拥有自己的task_struct结构体) 。
- 在没有线程之前 , 一个进程对应内核里的一个进程描述符 , 对应一个进程ID 。引入线程概念之后 , 一个用户进程下管理多个用户态线程 , 每个线程作为一个独立的调度实体 , 在内核中都有自己的进程描述符 。进程和内核的描述符变成了1:N的关系 。
经验总结扩展阅读
- 知天命是多少岁 古代年龄称谓
- 正常家庭一天用多少度电
- B站寂寞是什么意思
- 普通人直播带货能赚多少钱
- 2023双十一天猫消费券可以领几次 双十一天猫消费券怎么领取
- 2023淘宝双十一和双十二活动一样吗 双十一和双十二哪个优惠力度大
- 2023淘宝双十一活动力度大吗 淘宝双十一购物攻略有哪些
- 蒸双臭是什么食物
- 11月3日山东多地再现大风降温天气 半岛地区等地阵风可达7级以上
- 柿饼是热性还是凉性 多吃柿饼好不好