gpt4 book ai didi

c - 在多线程程序中处理异步信号

转载 作者:太空狗 更新时间:2023-10-29 16:41:19 24 4
gpt4 key购买 nike

Linux Programming Interface Book提到了一种在多线程程序中处理异步信号的方法:

  • All threads block all of the asynchronous signals that the process might receive. The simplest way to do this is to block the signals in the main thread before any other thread are created. Each subsequently created thread will inherit a copy of the main thread's signal mask.
  • create a single dedicated thread that accepts incoming signals using sigwaitinfo(), sigtimedwait() or sigwait().

The advantage of this approach is that asynchronously generated signals are received synchronously. As it accepts incoming signals, the dedicated thread can safely modify shared variables (under mutex control) and call non-async-safe functions. It can also signal condition variables, and emply other thread and process communication and synchronization mechanisms.

现在问题:

  1. 当内核想要传递信号时,它会选择任意进程内的线程之一。它可以从哪里知道将信号传递给专用线程?
  2. pthread API 是非 aync 安全函数。那么我们如何在信号处理程序中使用它们呢?

最佳答案

当内核传递一个进程导向信号时,它会选择没有阻塞信号的线程之一。这意味着它永远不会选择除信号处理线程之外的任何线程(它的行为就像信号在 sigwaitinfo() 或类似线程中被阻塞时未被阻塞)。换句话说:内核知道将信号传递到哪里,因为您已经安排好信号处理线程是唯一被允许将信号传递到的线程。

在信号处理程序中使用 pthreads API 或任何非异步信号安全函数。概述的解决方案不处理信号处理程序中的信号 - 它在 sigwaitinfo() 返回后处理信号处理线程的正常执行流中的信号。这允许它访问非异步信号安全的函数,这就是重点。

关于c - 在多线程程序中处理异步信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6223191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com