信号处理程序访问队列数据结构(竞赛条件?) [英] Signal handler accessing queue data structure (race condition?)

查看:112
本文介绍了信号处理程序访问队列数据结构(竞赛条件?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用C ++编写一个小型shell.

I'm currently writing a small shell in C++.

作业和与之关联的PID存储在作业指针(job *)的队列中.运行新作业时,有关该作业的信息将添加到队列中.由于可以同时处理多个作业,并且可以随时在Shell控制台中输入新作业,因此我有一个信号处理程序来等待终止的作业.

Jobs and the PIDs associated with them are stored within a queue of job pointers (job *). When a new job is run, information about it is added to the queue. Since multiple jobs can be handled simultaneously and new jobs can be entered at the shell's console at any time, I have a signal handler to wait on jobs which are terminated.

作业终止时,我需要从活动作业队列中删除其信息,然后将其移至终止作业的双端队列.但是,有可能在另一个作业停止时将用户的新作业添加到队列中.

When a job is terminated, I need to remove it's information from the active job queue and move it to my deque of terminated jobs. However, it is possible that a user's new job is being added to the queue when another job stops.

在这种情况下,他们的insert队列操作将被挂起,而我的信号处理程序将被调用,这将执行它的pop操作.

In such a case, their insert queue operation would be suspended and my signal handler would be called, which would perform it's pop operation.

我试图了解如何解决这种潜在的竞争状况,因为我认为在此过程中会发生腐败.我不能使用互斥锁,因为如果中断的父进程当时正在使用队列,则会发生死锁.

I'm trying to understand how I can resolve this potential race condition, as I imagine corruption can occur during this process. I cannot use a mutex, as a deadlock would occur if the interrupted parent process is using the queue at the time.

我看到了一些有关C++11能够进行用户声明的原子操作的信息,以及有关tasklet的信息.我不确定这些是否与我的问题有关.

I see some information about C++11 being capable of atomic operations as declared by the user, along with information regarding tasklets. I'm not sure if these are relevant to my question though.

一个有趣的示例shell(MSH- http://code.google.com/p/mini -shell-msh/)(我用作参考)似乎没有对这种情况进行任何处理.信号处理程序会立即修改作业列表以及主控制台.也许我在这里忽略了什么?

Interestingly enough, an example shell (MSH - http://code.google.com/p/mini-shell-msh/) which I am using as a reference does not appear to do any handling of such conditions. The signal handler immediately modifies the job list, along with the main console. Perhaps there is something I am overlooking here?

一如既往,所有反馈都得到应用.

As always, all feedback is appriciated.

推荐答案

您有几种避免竞争状况的方法.

You have several ways to avoid race condition.

  • 对作业指针使用无等待(原子)队列;
  • 使用任何其他类型的队列,但使用sigprocmask(在非处理程序代码中)并在sigaction调用中使用适当的sa_mask值对其进行保护;
  • 根本不使用信号处理程序,请使用一些非便携式系统调用,该调用允许以同步方式处理信号:在Linux中,可以使用signalfd,而不确定其他平台.
  • Use a wait free (atomic) queue for job pointers;
  • use any other kind of queue, but protect it with sigprocmask (in the non-handler code) and with proper sa_mask value in the sigaction call;
  • don't use signal handler at all, use some non-portable system call which allows working with signals in synchronous way: in Linux it is possible with signalfd, not sure about other platforms.

这篇关于信号处理程序访问队列数据结构(竞赛条件?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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