LispCookbook / LispCookbook/cl-cookbook

Elaborate on why BT:DESTROY-THREAD is a bad idea

Open
#386 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
1.1k
Forks
158
Avg merge
6d 3h
Merged PRs (30d)
2

Description

Augment https://lispcookbook.github.io/cl-cookbook/process.html#joining-on-a-thread-destroying-a-thread with the following:

Using `bt:destroy-thread` is a **bad** idea in the general case. Threads should instead finish on their own to do all the cleanup that they might need to do - one should never use `bt:destroy-thread` in production code. Destroying threads from outside is only feasible as a measure of last resort, as it can and eventually will leave the application in an unknown state.

It is better to `bt:interrupt-thread #'break` and select the bottommost `abort` restart in order to let the thread unwind completely. A programmatic version of this would be:

```lisp
(defun abort-thread (thread)
(flet ((thunk ()
;; We must call COMPUTE-RESTARTS in the dynamic context of the thread
;; that we want to abort, not of the thread that performs the
;; interruption.
(let* ((restarts (compute-restarts))
;; We assume that the last ABORT restart causes the whole
;; thread to unwind and exit gracefully.
(abort-restarts (remove-if-not (alexandria:curry #'eq 'abort)
restarts :key #'restart-name))
(abort-thread-restart (alexandria:lastcar abort-restarts)))
(invoke-restart abort-thread-restart))))
;; Interrupt the target thread with our thunk and force it to invoke the
;; ABORT restart, therefore initiating the unwind.
(bt:interrupt-thread thread thunk)))
```

TODO: check if this works on implementations other than SBCL.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked Common Lisp Cookbook section on joining on a thread and destroying a thread. Add the supplied warning, alternative, and example, then investigate the TODO about whether it works beyond SBCL; done means the section documents the portability result and the recommended guidance clearly.

Written by the indexing model from the issue text.

Assessment

Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.