You can use pthread_cancel() to kill a thread:
int pthread_cancel(pthread_t thread);
Note that the thread might not get a chance to do necessary cleanups, for example, release a lock, free memory and so on..So you should first use pthread_cleanup_push()
to add cleanup functions that will be called when the thread is cancelled. From man pthread_cleanup_push(3):
These functions manipulate the calling thread's stack of
thread-cancellation clean-up handlers. A clean-up handler is a
function that is automatically executed when a thread is cancelled (or
in various other circumstances described below); it might, for
example, unlock a mutex so that it becomes available to other threads
in the process.
Regarding the question of whether a thread will be cancelled if blocking or not, it's not guaranteed, note that the manual also mentions this:
A thread's cancellation type, determined by pthread_setcanceltype(3),
may be either asynchronous or deferred (the default for new
threads). Asynchronous cancelability means that the thread
can be canceled at any time (usually immediately, but the system does
not guarantee this). Deferred cancelability means that cancellation
will be delayed until the thread next calls a function that is a
cancellation point.
So this means that the only guaranteed behaviour is the the thread will be cancelled at a certain point after the call to pthread_cancel()
.
Note:
If you cannot change the thread code to add the cleanup handlers, then your only other choice is to kill the thread with pthread_kill(), however this is a very bad way to do it for the aforementioned reasons.