1

I have a double linked list protected by a pthread mutex. How can I access this list properly from a signal handler? (Here, the signal handler is the producer and some other code (thread) is the consumer.)

1.) I do not need to mutex_lock the list because the signal handler is the only part of the entire program that can access the list during the signal processing.

2.) But what happens if the signal handler e.g. adds something to the list and one of the other threads was currently accessing the linked list when the signal was raised? In this case I think that the code might crash when the signal handler returns (because of the list modification in the signal handler, which is not detected by the thread currently accessing the list).

Any idea on how to deal with this scenario?

Devvy
  • 43
  • 3
  • 1
    You *cannot* take a lock in a signal-handler. Hence, if you want to mix async-safety and thread-safety, the common subset is either: 1) Do not modify state shared between normal execution and signal-context or 2) Use lock-free atomics. You might be able to design a lock-free list if you have an architecture where `ATOMIC_POINTER_LOCK_FREE`. A doubly-linked list will not be easy to turn lock-free atomic. – EOF Jul 19 '17 at 21:45
  • See also https://stackoverflow.com/q/6223191/ – Nemo Jul 19 '17 at 21:49

1 Answers1

2

You don't.

You should make the signal handler can tell one of the threads that it got a signal. Then that thread (outside the signal handler) can access the list.

Alternatively, use signalfd and don't have a signal handler at all.

user253751
  • 57,427
  • 7
  • 48
  • 90
  • Thanks very much. signalfd is the correct way for me to handle the signal (SIGCHLD) properly w.r.t. the linked list. – Devvy Jul 20 '17 at 07:10