示例1:return退出线程调度函数
#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++ == 5){ return (void*)10; } }}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;}运行结果小伙伴们自己运行一下吧 。
示例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;}运行结果如下:
经验总结扩展阅读
- 知天命是多少岁 古代年龄称谓
- 正常家庭一天用多少度电
- B站寂寞是什么意思
- 普通人直播带货能赚多少钱
- 2023双十一天猫消费券可以领几次 双十一天猫消费券怎么领取
- 2023淘宝双十一和双十二活动一样吗 双十一和双十二哪个优惠力度大
- 2023淘宝双十一活动力度大吗 淘宝双十一购物攻略有哪些
- 蒸双臭是什么食物
- 11月3日山东多地再现大风降温天气 半岛地区等地阵风可达7级以上
- 柿饼是热性还是凉性 多吃柿饼好不好