弄懂线程取消的一个例子

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多线程父线程向子线程传值问题及解决》文章总结了5种解决父子之间数据传递困扰的解决方案,包括ThreadLocal+TaskDecorator、UserUtils、CustomTaskDeco... 目录1 背景2 ThreadLocal+TaskDecorator3 RequestContextH

java父子线程之间实现共享传递数据

《java父子线程之间实现共享传递数据》本文介绍了Java中父子线程间共享传递数据的几种方法,包括ThreadLocal变量、并发集合和内存队列或消息队列,并提醒注意并发安全问题... 目录通过 ThreadLocal 变量共享数据通过并发集合共享数据通过内存队列或消息队列共享数据注意并发安全问题总结在 J

使用Python在Excel中创建和取消数据分组

《使用Python在Excel中创建和取消数据分组》Excel中的分组是一种通过添加层级结构将相邻行或列组织在一起的功能,当分组完成后,用户可以通过折叠或展开数据组来简化数据视图,这篇博客将介绍如何使... 目录引言使用工具python在Excel中创建行和列分组Python在Excel中创建嵌套分组Pyt

异步线程traceId如何实现传递

《异步线程traceId如何实现传递》文章介绍了如何在异步请求中传递traceId,通过重写ThreadPoolTaskExecutor的方法和实现TaskDecorator接口来增强线程池,确保异步... 目录前言重写ThreadPoolTaskExecutor中方法线程池增强总结前言在日常问题排查中,

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

C语言线程池的常见实现方式详解

《C语言线程池的常见实现方式详解》本文介绍了如何使用C语言实现一个基本的线程池,线程池的实现包括工作线程、任务队列、任务调度、线程池的初始化、任务添加、销毁等步骤,感兴趣的朋友跟随小编一起看看吧... 目录1. 线程池的基本结构2. 线程池的实现步骤3. 线程池的核心数据结构4. 线程池的详细实现4.1 初

Java子线程无法获取Attributes的解决方法(最新推荐)

《Java子线程无法获取Attributes的解决方法(最新推荐)》在Java多线程编程中,子线程无法直接获取主线程设置的Attributes是一个常见问题,本文探讨了这一问题的原因,并提供了两种解决... 目录一、问题原因二、解决方案1. 直接传递数据2. 使用ThreadLocal(适用于线程独立数据)

C#如何优雅地取消进程的执行之Cancellation详解

《C#如何优雅地取消进程的执行之Cancellation详解》本文介绍了.NET框架中的取消协作模型,包括CancellationToken的使用、取消请求的发送和接收、以及如何处理取消事件... 目录概述与取消线程相关的类型代码举例操作取消vs对象取消监听并响应取消请求轮询监听通过回调注册进行监听使用Wa

线程的四种操作

所属专栏:Java学习        1. 线程的开启 start和run的区别: run:描述了线程要执行的任务,也可以称为线程的入口 start:调用系统函数,真正的在系统内核中创建线程(创建PCB,加入到链表中),此处的start会根据不同的系统,分别调用不同的api,创建好之后的线程,再单独去执行run(所以说,start的本质是调用系统api,系统的api

java线程深度解析(六)——线程池技术

http://blog.csdn.net/Daybreak1209/article/details/51382604 一种最为简单的线程创建和回收的方法: [html]  view plain copy new Thread(new Runnable(){                @Override               public voi