# Signaling threads that are waiting on mutexes

**URL:** <https://swi-prolog.discourse.group/t/signaling-threads-that-are-waiting-on-mutexes/8875>\
**Category:** General\
**Created:** [March 11, 2025, 1:43pm UTC](https://swi-prolog.discourse.group/t/signaling-threads-that-are-waiting-on-mutexes/8875 "2025-03-11T13:43:37Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![esad](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/esad/32/884_2.png) [@esad](https://swi-prolog.discourse.group/u/esad)\
**Post date:** [March 11, 2025, 1:43pm UTC](https://swi-prolog.discourse.group/t/signaling-threads-that-are-waiting-on-mutexes/8875/1 "2025-03-11T13:43:37Z")

</div>

It seems that it’s not possible to abort a thread that is waiting on some mutex:

```prolog
?- mutex_create(M), mutex_lock(M), thread_create((mutex_lock(M), write(never_here)), Tid).
% then later after thread has had opportunity to start:
?- thread_signal($Tid, abort), thread_join($Tid, Result). % stuck

```

Is there a way around it?

---

<div class="post-metadata">

**Author:** ![esad](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/esad/32/884_2.png) [@esad](https://swi-prolog.discourse.group/u/esad)\
**Post date:** [March 11, 2025, 1:53pm UTC](https://swi-prolog.discourse.group/t/signaling-threads-that-are-waiting-on-mutexes/8875/2 "2025-03-11T13:53:10Z")

</div>

I understand that (following the docs), the thread that is waiting on a mutex will never have opportunity to receive the signal. But maybe abort or some other kind of fatal signal should have special treatment and allow killing “stuck” threads?

---

<div class="post-metadata">

**Author:** ![jan](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/jan/32/4_2.png) [@jan](https://swi-prolog.discourse.group/u/jan)\
**Post date:** [March 11, 2025, 2:21pm UTC](https://swi-prolog.discourse.group/t/signaling-threads-that-are-waiting-on-mutexes/8875/3 "2025-03-11T14:21:20Z")

</div>

Works fine on Linux, be it slow. This requires pthread\_mutex\_timedlock() though, which does not exist on all platforms. I know of no reliable way to achieve this in a portable way.

Also on Linux, it is merely intended for interactive usage as the target thread may delay up to 0.25 sec.

Mutexes should in general be avoided. The rather complicated Prolog control flow, including exceptions, failure, backtracking and non-determinism make it really easy to deadlock when using mutexes. If unavoidable, use with\_mutex/2 and make sure the called goal will terminate quickly. If broken into lock and unlock, use setup\_call\_cleanup/3 and again, make sure there is a cleanup quickly (notably in this case, do not leave a choicepoint).

What is the more high level goal?
