弄懂线程取消的一个例子

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

相关文章

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线程... 目录异常信息触发场景找到版本发布更新的说明从版本更新信息可以看到该默认逻辑已经去除总结异常信息触发场景复

JAVA保证HashMap线程安全的几种方式

《JAVA保证HashMap线程安全的几种方式》HashMap是线程不安全的,这意味着如果多个线程并发地访问和修改同一个HashMap实例,可能会导致数据不一致和其他线程安全问题,本文主要介绍了JAV... 目录1. 使用 Collections.synchronizedMap2. 使用 Concurren

Spring Boot3虚拟线程的使用步骤详解

《SpringBoot3虚拟线程的使用步骤详解》虚拟线程是Java19中引入的一个新特性,旨在通过简化线程管理来提升应用程序的并发性能,:本文主要介绍SpringBoot3虚拟线程的使用步骤,... 目录问题根源分析解决方案验证验证实验实验1:未启用keep-alive实验2:启用keep-alive扩展建

Java终止正在运行的线程的三种方法

《Java终止正在运行的线程的三种方法》停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作,停止一个线程可以用Thread.stop()方法,但最好不要用它,本文给大家介绍了... 目录前言1. 停止不了的线程2. 判断线程是否停止状态3. 能停止的线程–异常法4. 在沉睡中停止5

Java捕获ThreadPoolExecutor内部线程异常的四种方法

《Java捕获ThreadPoolExecutor内部线程异常的四种方法》这篇文章主要为大家详细介绍了Java捕获ThreadPoolExecutor内部线程异常的四种方法,文中的示例代码讲解详细,感... 目录方案 1方案 2方案 3方案 4结论方案 1使用 execute + try-catch 记录

Spring Boot 中正确地在异步线程中使用 HttpServletRequest的方法

《SpringBoot中正确地在异步线程中使用HttpServletRequest的方法》文章讨论了在SpringBoot中如何在异步线程中正确使用HttpServletRequest的问题,... 目录前言一、问题的来源:为什么异步线程中无法访问 HttpServletRequest?1. 请求上下文与线