弄懂线程取消的一个例子

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通过interrupt()通知线程停止而非强制,确保线程自主处理中断,避免数据损坏,线程池的shutdown()等待任务完成,shutdownNow()强制中断... 目录为什么不强制停止为什么 Java 不提供强制停止线程的能力呢?如何用interrupt停止线程s

python 线程池顺序执行的方法实现

《python线程池顺序执行的方法实现》在Python中,线程池默认是并发执行任务的,但若需要实现任务的顺序执行,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋... 目录方案一:强制单线程(伪顺序执行)方案二:按提交顺序获取结果方案三:任务间依赖控制方案四:队列顺序消

python中update()函数的用法和一些例子

《python中update()函数的用法和一些例子》update()方法是字典对象的方法,用于将一个字典中的键值对更新到另一个字典中,:本文主要介绍python中update()函数的用法和一些... 目录前言用法注意事项示例示例 1: 使用另一个字典来更新示例 2: 使用可迭代对象来更新示例 3: 使用

python连接sqlite3简单用法完整例子

《python连接sqlite3简单用法完整例子》SQLite3是一个内置的Python模块,可以通过Python的标准库轻松地使用,无需进行额外安装和配置,:本文主要介绍python连接sqli... 目录1. 连接到数据库2. 创建游标对象3. 创建表4. 插入数据5. 查询数据6. 更新数据7. 删除

SpringBoot实现虚拟线程的方案

《SpringBoot实现虚拟线程的方案》Java19引入虚拟线程,本文就来介绍一下SpringBoot实现虚拟线程的方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录什么是虚拟线程虚拟线程和普通线程的区别SpringBoot使用虚拟线程配置@Async性能对比H

在Java中实现线程之间的数据共享的几种方式总结

《在Java中实现线程之间的数据共享的几种方式总结》在Java中实现线程间数据共享是并发编程的核心需求,但需要谨慎处理同步问题以避免竞态条件,本文通过代码示例给大家介绍了几种主要实现方式及其最佳实践,... 目录1. 共享变量与同步机制2. 轻量级通信机制3. 线程安全容器4. 线程局部变量(ThreadL

Linux线程同步/互斥过程详解

《Linux线程同步/互斥过程详解》文章讲解多线程并发访问导致竞态条件,需通过互斥锁、原子操作和条件变量实现线程安全与同步,分析死锁条件及避免方法,并介绍RAII封装技术提升资源管理效率... 目录01. 资源共享问题1.1 多线程并发访问1.2 临界区与临界资源1.3 锁的引入02. 多线程案例2.1 为

Java中的xxl-job调度器线程池工作机制

《Java中的xxl-job调度器线程池工作机制》xxl-job通过快慢线程池分离短时与长时任务,动态降级超时任务至慢池,结合异步触发和资源隔离机制,提升高频调度的性能与稳定性,支撑高并发场景下的可靠... 目录⚙️ 一、调度器线程池的核心设计 二、线程池的工作流程 三、线程池配置参数与优化 四、总结:线程

WinForm跨线程访问UI及UI卡死的解决方案

《WinForm跨线程访问UI及UI卡死的解决方案》在WinForm开发过程中,跨线程访问UI控件和界面卡死是常见的技术难题,由于Windows窗体应用程序的UI控件默认只能在主线程(UI线程)上操作... 目录前言正文案例1:直接线程操作(无UI访问)案例2:BeginInvoke访问UI(错误用法)案例

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

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