弄懂线程取消的一个例子

2024-05-03 11:32
文章标签 线程 取消 例子 弄懂

本文主要是介绍弄懂线程取消的一个例子,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

今天结束了,仍然在看 《Programming with posix threads》这本书,关于线程的取消。本来想总结一下线程推迟取消 异步取消 以及清除这些概念,发现有个人总结的特别的好,链接拉过来给大家看一下。
https://www.cnblogs.com/lijunamneg/archive/2013/01/25/2877211.html

在这里想写一下弄懂这章其中一个例子的过程,温习一下思考过程。
这主要是个承包转包线程的例子,算是工作组模型吧。
程序执行时创建承包线程,在承包线程里面又创建了很多的子线程,子线程叫转包线程,不过是一种叫法,无需多想。看过链接里文章会知道,在取消线程的时候可以指定取消时要执行的清除函数。具体细节如附程序所示。
特别的,是在清除函数中执行了对部分承包线程的取消工作。
我产生了些困惑,在这部分取消工作当中。为什么下标是从team->join_i 开始的呢?
一开始我这么想的,thread_routine 创建转包线程完成一次对每个线程执行pthread_join. 在接到取消信号的时正好执行对某个的pthread_join的取消点,剩余没有join的线程就被清理掉了,但是,就是已经join的线程就不需要清理吗。我之所以会这么问,当时并不清楚join函数执行是阻塞的 。查一下pthread_join的文档就应该知道,这个函数是阻塞调用的,一旦返回就说明程序已经结束了,也就没有了清理的必要。
每次我试图告诉你发现某个接口的秘密,就会突然发现,文档已经写得很完美了,尤其对于这种比较成熟的库而言。比如pthread_join的文档告诉你函数返回保证了什么,join同一个线程两次对不对,不能join的线程是怎么样的。什么样的线程是joinable的,调用joinable的线程被取消被joinable的线程会怎么样。都告诉你了, 所以还是遇到问题首选看文档啊:
http://man7.org/linux/man-pages/man3/pthread_join.3.html
同样的, pthread_cancel 文档也会告诉你很多
http://man7.org/linux/man-pages/man3/pthread_cancel.3.html

其实这个例子中创建的线程是个无限循环不太好,直接运行代码结果一定从第0个线程开始取消的,因为每个线程都在被取消之前永远不终止,所以承包线程一直阻塞在第一个pthread_join函数调用上。
我们来改一下程序吧,增加一个函数,有区别的创建转包线程。

void *worker_routine1 (void *arg)
{int counter;for (counter = 0; ; counter++;counter < 1000000)if ((counter % 1000) == 0)pthread_testcancel ();
}

在创建前3个线程的时候用worker_routine1() , 后面的线程用work_routine(). 这样在取消的时候前20个线程已经终止了。所以clean up 的时候只需要清理还没有被join的函数就可以了。结果是从下标3开始取消的。

运行结果
这里写图片描述

附原始代码(修改之前的)


/** cancel_subcontract.c** Demonstrate how a thread can handle cancellation and in turn* cancel a set of worker ("subcontractor") threads.** Special notes: On a Solaris 2.5 uniprocessor, this test will* hang unless an LWP is created for each worker thread by* calling thr_setconcurrency(), because threads are not* timesliced.*/
#include <pthread.h>
#include "errors.h"#define THREADS 5/** Structure that defines the threads in a "team".*/
typedef struct team_tag {int          join_i;                 /* join index */pthread_t    workers[THREADS];       /* thread identifiers */
} team_t;/** Start routine for worker threads. They loop waiting for a* cancellation request.*/
void *worker_routine (void *arg)
{int counter;for (counter = 0; ; counter++)if ((counter % 1000) == 0)pthread_testcancel ();
}/** Cancellation cleanup handler for the contractor thread. It* will cancel and detach each worker in the team.*/
void cleanup (void *arg)
{team_t *team = (team_t *)arg;int count, status;for (count = team->join_i; count < THREADS; count++) {status = pthread_cancel (team->workers[count]);if (status != 0)err_abort (status, "Cancel worker");status = pthread_detach (team->workers[count]);if (status != 0)err_abort (status, "Detach worker");printf ("Cleanup: cancelled %d\n", count);}
}/** Thread start routine for the contractor. It creates a team of* worker threads, and then joins with them. When cancelled, the* cleanup handler will cancel and detach the remaining threads.*/
void *thread_routine (void *arg)
{team_t team;                        /* team info */int count;void *result;                       /* Return status */int status;for (count = 0; count < THREADS; count++) {status = pthread_create (&team.workers[count], NULL, worker_routine, NULL);if (status != 0)err_abort (status, "Create worker");}pthread_cleanup_push (cleanup, (void*)&team);for (team.join_i = 0; team.join_i < THREADS; team.join_i++) {status = pthread_join (team.workers[team.join_i], &result);if (status != 0)err_abort (status, "Join worker");}pthread_cleanup_pop (0);return NULL;
}int main (int argc, char *argv[])
{pthread_t thread_id;int status;#ifdef sun/** On Solaris 2.5, threads are not timesliced. To ensure* that our threads can run concurrently, we need to* increase the concurrency level to at least 2 plus THREADS* (the number of workers).*/DPRINTF (("Setting concurrency level to %d\n", THREADS+2));thr_setconcurrency (THREADS+2);
#endifstatus = pthread_create (&thread_id, NULL, thread_routine, NULL);if (status != 0)err_abort (status, "Create team");sleep (5);printf ("Cancelling...\n");status = pthread_cancel (thread_id);if (status != 0)err_abort (status, "Cancel team");status = pthread_join (thread_id, NULL);if (status != 0)err_abort (status, "Join team");
}

这篇关于弄懂线程取消的一个例子的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/956639

相关文章

Linux线程之线程的创建、属性、回收、退出、取消方式

《Linux线程之线程的创建、属性、回收、退出、取消方式》文章总结了线程管理核心知识:线程号唯一、创建方式、属性设置(如分离状态与栈大小)、回收机制(join/detach)、退出方法(返回/pthr... 目录1. 线程号2. 线程的创建3. 线程属性4. 线程的回收5. 线程的退出6. 线程的取消7.

Linux下进程的CPU配置与线程绑定过程

《Linux下进程的CPU配置与线程绑定过程》本文介绍Linux系统中基于进程和线程的CPU配置方法,通过taskset命令和pthread库调整亲和力,将进程/线程绑定到特定CPU核心以优化资源分配... 目录1 基于进程的CPU配置1.1 对CPU亲和力的配置1.2 绑定进程到指定CPU核上运行2 基于

Javaee多线程之进程和线程之间的区别和联系(最新整理)

《Javaee多线程之进程和线程之间的区别和联系(最新整理)》进程是资源分配单位,线程是调度执行单位,共享资源更高效,创建线程五种方式:继承Thread、Runnable接口、匿名类、lambda,r... 目录进程和线程进程线程进程和线程的区别创建线程的五种写法继承Thread,重写run实现Runnab

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

Java 线程安全与 volatile与单例模式问题及解决方案

《Java线程安全与volatile与单例模式问题及解决方案》文章主要讲解线程安全问题的五个成因(调度随机、变量修改、非原子操作、内存可见性、指令重排序)及解决方案,强调使用volatile关键字... 目录什么是线程安全线程安全问题的产生与解决方案线程的调度是随机的多个线程对同一个变量进行修改线程的修改操

Java中实现线程的创建和启动的方法

《Java中实现线程的创建和启动的方法》在Java中,实现线程的创建和启动是两个不同但紧密相关的概念,理解为什么要启动线程(调用start()方法)而非直接调用run()方法,是掌握多线程编程的关键,... 目录1. 线程的生命周期2. start() vs run() 的本质区别3. 为什么必须通过 st

Linux实现线程同步的多种方式汇总

《Linux实现线程同步的多种方式汇总》本文详细介绍了Linux下线程同步的多种方法,包括互斥锁、自旋锁、信号量以及它们的使用示例,通过这些同步机制,可以解决线程安全问题,防止资源竞争导致的错误,示例... 目录什么是线程同步?一、互斥锁(单人洗手间规则)适用场景:特点:二、条件变量(咖啡厅取餐系统)工作流

Java中常见队列举例详解(非线程安全)

《Java中常见队列举例详解(非线程安全)》队列用于模拟队列这种数据结构,队列通常是指先进先出的容器,:本文主要介绍Java中常见队列(非线程安全)的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一.队列定义 二.常见接口 三.常见实现类3.1 ArrayDeque3.1.1 实现原理3.1.2

SpringBoot3中使用虚拟线程的完整步骤

《SpringBoot3中使用虚拟线程的完整步骤》在SpringBoot3中使用Java21+的虚拟线程(VirtualThreads)可以显著提升I/O密集型应用的并发能力,这篇文章为大家介绍了详细... 目录1. 环境准备2. 配置虚拟线程方式一:全局启用虚拟线程(Tomcat/Jetty)方式二:异步

如何解决Druid线程池Cause:java.sql.SQLRecoverableException:IO错误:Socket read timed out的问题

《如何解决Druid线程池Cause:java.sql.SQLRecoverableException:IO错误:Socketreadtimedout的问题》:本文主要介绍解决Druid线程... 目录异常信息触发场景找到版本发布更新的说明从版本更新信息可以看到该默认逻辑已经去除总结异常信息触发场景复