本文介绍了POSIX线程和信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图了解如何POSIX线程和POSIX信号相互作用的复杂性。特别是我感兴趣的:


  • 什么来控制线程的信号被传递到的最佳方式(假定它不是在首位是致命的)?

  • 什么是告诉另一个线程(实际上可能是忙),该信号已经到来的最好方法? (我已经知道这是一个坏主意,用从信号处理程序的pthread条件变量是。)

  • 如何安全地处理传递一个信号发生了其他线程的信息?这是否需要在信号处理程序会发生什么? (我做的不是一般的想杀死其他线程。我需要一个远微妙的方法)

有关为什么我要这样的参考,我研究如何将包来支持线程​​转换,或拆分它,至少做一些有用的部分支持线程。信号是特别感兴趣的那些部分中的一个。


解决方案

As @zoli2k indicated, explicitly nominating a single thread to handle all signals you want handled (or a set of threads each with specific signal responsibilities), is a good technique.

I won't say "best," but here's my recommendation:

Block all desired signals in main, so that all threads are inherit that signal mask. Then, fashion the special signal receiving thread as a signal-driven event loop, dispatching newly arrived signals as some other intra-thread communication.

The simplest way to do this is to have the thread accept signals in a loop using sigwaitinfo or sigtimedwait. The thread then converts the signals somehow, perhaps broadcasting a pthread_cond_t, waking up other threads with more I/O, enqueuing a command in an application-specific thread-safe queue, whatever.

Alternatively, the special thread could allow signals to be delivered to a signal handler, unmasking for delivery only when ready to handle signals. (Signal delivery via handlers tends to be more error-prone than signal acceptance via the sigwait family, however.) In this case, the receiver's signal handler performs some simple and async-signal-safe action: setting sig_atomic_t flags, calling sigaddset(&signals_i_have_seen_recently, latest_sig), write() a byte to a non-blocking self-pipe, etc. Then, back in its masked main loop, the thread communicates receipt of the signal to other threads as above.

(UPDATED @caf rightly points out that sigwait approaches are superior.)

这篇关于POSIX线程和信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:36
查看更多