我是否过度设计了每线程信号阻塞? [英] Am I over-engineering per-thread signal blocking?

查看:38
本文介绍了我是否过度设计了每线程信号阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我通常希望拦截 SIGINTSIGTERM 信号以便正常关闭.

In my applications, I generally want to intercept SIGINT and SIGTERM signals in order to close down gracefully.

为了防止工作线程窃取"信号,我在每个入口点这样做:

In order to prevent worker threads from "stealing" signals, I do this in the entrypoint for each:

// Block signals in this thread
sigset_t signal_set;
sigaddset(&signal_set, SIGINT);
sigaddset(&signal_set, SIGTERM);
sigaddset(&signal_set, SIGHUP);
sigaddset(&signal_set, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &signal_set, NULL);

如果我不这样做,当我执行 Ctrl+C 时,有时(未指定哪个线程将获得信号)我的处理程序在不会调用基线程 —相反,信号只是从工作线程中终止进程.这显然不酷.

If I don't, when I perform Ctrl+C, some of the time (it's unspecified as to which thread will get the signal) my handlers in the base thread won't be invoked — instead, the signal just terminates the process from within the worker thread. This is obviously not cool.

所以我有一个信号处理线程并在其他地方阻塞信号.

So I have one signal-handling thread and block signals everywhere else.

然而,我没有注意到其他人这样做,很容易忘记这样做,而且它也不完全便携.我还缺少一些更简单的技巧吗?

However, I don't notice anybody else doing this, it's easy enough to forget to do, and it's also not entirely portable. Is there some more simple trick I'm missing?

参考文献:

推荐答案

我觉得这是一件非常合理的事情.

I find it a perfectly reasonable thing to do.

您可以在生成任何其他线程之前阻止 main 中的信号.产生的线程将继承创建者线程信号掩码,您只能在信号处理线程中解除信号阻塞(只有当该线程也产生其他线程时才小心).

You could block the signals in main, before any other thread is spawned. The spawned threads will inherit the creator thread signal mask and you can unblock signals only in the signal handling thread (being careful only if that thread spawns other threads as well).

或者你可以让信号在任何地方都被阻塞,并通过 sigwait 和信号处理线程中的朋友显式地处理它们.

Or you can leave the signals blocked everywhere and explicitly handle them via sigwait and friends in the signal handling thread.

这篇关于我是否过度设计了每线程信号阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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