运行结果小伙伴们自己运行一下吧 。
示例2:pthread_exit函数
void pthread_exit(void *retval);功能: 退出调用线程 。一个进程中的多个线程是共享该进程的数据段,因此,通常线程退出后所占用的资源并不会释放 。参数: retval:存储线程退出状态的指针 。返回值:无#include <stdio.h>#include <pthread.h>#include <unistd.h>void* pthreadrun(void* arg){ int count = 0; while (1){ printf(" new threaad is running, pid is %d, thread id is %p\n", getpid(), pthread_self()); sleep(1); if (++count == 3){ pthread_exit(NULL); } }}int main(){ pthread_t thread; pthread_create(&thread, NULL, pthreadrun, NULL); while (1){ printf("main thread is running, pid is %d, thread id is %p\n", getpid(), pthread_self()); sleep(1); } return 0;}在线程调度函数中pthread_exit(NULL)等价于return。
示例3:pthread_cancel函数
int pthread_cancel(pthread_t thread);功能: 杀死(取消)线程参数: thread:目标线程ID返回值: 成功:0 失败:出错编号注意:线程的取消不是实时的,而是有一定的延时 。需要等待线程到达某个取消点(检查点) 。
#include <stdio.h>#include <pthread.h>#include <unistd.h>void* pthreadrun(void* arg){ int count = 0; while (1){ printf(" new threaad is running, pid is %d, thread id is %p,count is %d\n", getpid(), pthread_self(),count); sleep(1); }}int main(){ pthread_t thread; pthread_create(&thread, NULL, pthreadrun, NULL); int count = 0; while (1){ printf("main thread is running, pid is %d, thread id is %p,count is %d\n", getpid(), pthread_self(),count); sleep(1); if (++count == 3){ pthread_cancel(thread); printf("new thread is canceled...\n"); } } return 0;}运行结果如下:

文章插图
主线程把子线程谋杀了,只能取消同一个进程中的线程,还可以根据count的值看出,每个线程有自己独立的PCB,在PCB中存在自己的栈区 。
线程等待线程等待的原因:
- 已经退出的线程,其空间没有被释放,仍然在进程的地址空间内 。
- 创建新的线程不会复用刚才退出线程的地址空间 。
推荐阅读
- 1斤等于多少磅 一斤等于多少磅
- 荣耀v40屏幕材质_荣耀v40屏幕多大
- 香奈儿山茶花洗面奶味道不一样了_香奈儿洗面奶味道变了
- 怎样快速赚钱(期货1万一年挣1亿)
- Kotlin Mockito使用方法
- 一文理解Cookie、Session
- 一 网络安全:信息收集之玩转nmap(理论篇)
- 荣耀50多久上市_荣耀50什么时候上市
- 华为nova8安兔兔跑分_华为nova8跑分多少
- 天玑1100相当于骁龙多少处理器_天玑1100相当于骁龙什么水平