3

In our server code we are using poll() system call for monitoring client sockets. The poll() is called with a large timeout value. So the thread calling poll() gets blocked for I/O.

As per the flow, we have a scenario where we need to terminate thread that blocked in poll() from a different thread. I have came across pthread_kill() and pthread_cancel() functions, which can terminate the target thread blocked for I/O.

By reading the man pages, both these functions seems to work fine. Few links on internet suggested that both of these functions are dangerous to use.

Is there any alternative way to terminate the thread blocked for I/O ? If not, which of these functions is recommended to use.

8
  • 4
    Killing a thread is risky. See this question. Sep 18, 2018 at 17:23
  • 1
    Wake up from poll more often and test a termination flag set by the other thread. If the flag says terminate, terminate. Otherwise loop around and poll again until you hit the broader exit condition. Thread kill should be a last resort. as it can leave you with an unstable program Sep 18, 2018 at 17:34
  • 3
    Since you have this tagged linux, one approach is to include an eventfd() descriptor in the ones you poll on, and signal it when the polling thread should exit (And have that thread do so gracefully when that fd becomes readable).
    – Shawn
    Sep 18, 2018 at 17:56
  • 1
    @R.. Killing a threat is generally understood to mean to cause it's execution to stop immediately and irrevocably. Whether or not a particular threading API allows it is another question. Sep 18, 2018 at 18:05
  • 1
    @R.. You're right about that. Still, killing a thread is risky and still, there is such a thing as killing a thread. This information is still relevant to OP since this is what they are attempting to do, regardless of the impossibility of doing it with their chosen API. Sep 18, 2018 at 18:20

3 Answers 3

3

An easy and clean option is to create a "signal" pipe. That is, call pipe, take the file descriptor for the "read" end and add it to your list of poll file descriptors (with POLLIN). Then, whenever you want to unblock the thread which is waiting in poll, just write a byte to the write end of the pipe. The pipe, having received data, will return as readable in the blocked thread. You can even specify different "commands" by varying the value of the byte written.

(You'll need to read the byte from the pipe before it can be re-used of course.)

2
  • 2
    +1 and a side note: Since OP is [already] doing sockets [and, thus, already familiar with them], we could replace the pipe with an AF_UNIX socket. It may provide better R/T response. Dunno. Sep 18, 2018 at 20:26
  • +1, This is a really good approach when it works, but there are some operations that block that don't have an associated file descriptor you can poll. Sep 19, 2018 at 0:09
2

Depending on the exact implementation of your thread library, it's very likely the thread won't even return from poll when being killed - so, you probably won't even achieve what you want.

You need to be very careful not to create memory leaks, and still are very likely to create a file descriptor leak by killing the thread that owns it (note, thread resources, in contrary to processes, aren't "cleaned up" by the system).

It is generally safer to use shorter timeout periods and poll a terminate flag in-between, or use signals to interrupt the system call, then terminate the thread under its own control, freeing all allocated resources.

15
  • 2
    @R. I think it's pretty obvious what's meant. In case you don't like me call it killing, call it forcibly terminate
    – tofro
    Sep 18, 2018 at 18:32
  • 2
    @R. just like processes - Still, the command is called kill. Even there, and has always been.
    – tofro
    Sep 18, 2018 at 18:47
  • 2
    That's what I'm saying. And, still, it's called kill. Even if it can't kill processes. Even if it can be used to wake up processes which is sortof the opposite. I think you are nitpicking on terminology.
    – tofro
    Sep 18, 2018 at 18:52
  • 2
    The posix thread functions that terminate a thread do this by sending a signal to it (just like kill does when sending a signal to a process). Most pthread libs do the same thing using non-terminating signals, so need co-operation from the thread in order to end the thread and not the whole process. So what? Still looks like kill to me. But arguing whether you can "kill" a thread or not doesn't really answer the question.
    – tofro
    Sep 18, 2018 at 19:08
  • 2
    @R.. pthread_cancel sends a [special] signal to the target thread, which intercepts it, does a bit of cleanup, and terminates. One can mask off signals via pthread_sigmask which is wrapper around sigprocmask [to prevent accidental masking of the signal that pthread_cancel uses] and it works on a per-thread basis. kill(2) can be given a thread id (from gettid) instead of a process id (from getpid) Sep 18, 2018 at 23:17
2

There is no such thing as killing a thread.

The poorly-named pthread_kill function is a threads analogue of the poorly-named kill function, which sends a signal to process. The name kill historically made sense in that the default action of many signals is to kill the process. But this default action of killing the process does not depend on whether the signal was sent to the process or a particular thread - either way, the process terminates.

The only time pthread_kill is useful is when you want to invoke a signal handler on another thread. Unless you are certain that the signal handler could not have interrupted any function that is not async-signal-safe, the signal handler is limited to calling functions which are async-signal-safe, and thereby cannot even act to end the thread's lifetime (pthread_exit is not async-signal-safe).

If you're okay with the thread eventually terminating as a result of the call, pthread_cancel is the right way to end a thread stuck in a blocking operation. In order to use it safely, though, you need to make heavy use of pthread_cleanup_push and pthread_cleanup_pop.

If you don't want the thread to terminate, signals are your only option. You have two choices:

  1. Install a signal handler (can be a no-op) using sigaction without SA_RESTART, so that it causes EINTR. Since there are inherent race conditions in this approach (if you send the signal just before the blocking syscall is entered, rather than once it's blocked, the signal won't do anything) you need to repeatedly send the signal, with exponential back-off so as not to starve the target of execution time, until the target confirms via some other synchronization mechanism (a POSIX semaphore works well) that it got the message.

  2. Install a signal handler that will longjmp. In order to do this safely you need to control the context from which it can happen; the easiest way to do this is to keep it blocked in the signal mask normally, only unmasking it when the jmp_buf is valid around a blocking call. The blocking function you call needs to be async-signal-safe, and it needs to not be one which allocates or frees resources (like open or close) since you will lose knowledge of whether it completed when you handle the signal. Of course the jmp_buf, or a pointer to it, needs to be a thread-local object (_Thread_local/__thread) in order for this to work at all.

1
  • Someone's upset about me pointing out that there's no such thing as killing a thread (in the context of POSIX threads, for which the question is tagged). Sep 18, 2018 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.