C信号处理程序难题中的竞赛条件 [英] Race condition in C signal handlers puzzle

查看:45
本文介绍了C信号处理程序难题中的竞赛条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道在C语言中处理信号时如何避免出现竞争状况.每次我的程序收到信号时,我都希望它更改(全局)链接列表.非常重要的一点是,不要错过任何信号,同样重要的是,在处理程序执行期间,不要更改正在修改的全局链表.

I need to know how to avoid a race condition when handling signals in C. Each time my program receives a signal, I want it to alter a (global) linked list. It is vitally important that I not miss a signal, and equally important that the global linked list I'm modifying not be changed while the handler is executing.

问题是,如果我收到一个信号,然后启动处理程序,但随后又被另一个信号打断了.(据我所知)触发了信号处理程序的新执行,该处理程序将在相同的全局数据集上运行-不允许!

The problem is, if I receive a signal, and start the handler, but am then interrupted by another signal. This (as I understand it) triggers a new execution of the signal handler, which will operate on the same global dataset - not permissible!

我不能使用锁,因为如果第一个处理程序调用被中断,它自然不会释放该锁供中断的处理程序使用.那么,我该怎么做呢?有什么主意吗?

I can't use a lock, because if the first handler call is interrupted, it will naturally never free the lock for the interrupting handler to pick up. So, how do I do it? Any idea?

推荐答案

如果您有幸在多线程环境中工作,最好的方法之一是让全局链接列表仅由单独的线程控制.中断会将请求排队到该线程中(可以很快地执行操作,例如,只需传递一个指针即可),然后该线程将按程序遍历每个请求并修改链接列表.这允许无锁执行.

If you have the luck to be working in a multi-threaded environment, one of the best ways is to have the global linked list controlled exclusively by a separate thread. Interrupts would enqueue requests to this thread (something that would be executed very quickly, say, by simply passing a pointer), and then the thread would procedurally go through each request and modify the linked list. This allows lockless execution.

当然,您必须依靠操作系统的消息传递垃圾,因此这不是一个选择.

Of course, you have to rely on your OS's message passing junk, so that may not be an option.

这篇关于C信号处理程序难题中的竞赛条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆