Subject: bug#63311: 30.0.50; [PATCH] smtpmail-send-it split

From: Manuel Giraud <[email-masked]>
Date: Fri, 12 May 2023 08:24:36 +0200

Eli Zaretskii <[email-masked]> writes:

>> From: Manuel Giraud <[email-masked]>
>> Cc: [email-masked]
>> Date: Thu, 11 May 2023 22:59:20 +0200
>> 
>> (defun my-problem ()
>>   (interactive)
>>   (let ((buf (generate-new-buffer "*foo*")))
>>     (with-current-buffer buf
>>       (insert "secret message"))
>>     (unwind-protect
>> 	(make-thread #'(lambda ()
>> 			 (with-current-buffer buf
>> 			   (sit-for 10)
>> 			   (message (buffer-string)))))
>>       (kill-buffer buf))))
>> --8<---------------cut here---------------end--------------->8---
>> 
>> The thread won't have a chance to do its job since the buffer will
>> already be dead.
>
> Of course.  So you cannot do that, obviously.  Cleanup that gets in
> the way of code you run in a thread must be done after thread-join
> returns, or when thread-live-p returns nil for the thread.  Or use
> some other synchronization method.  There could be several such
> threads alive at the same time, btw.
>
> In the unwind-protect handler of the main thread you can only do
> cleanup of stuff that the thread doesn't need, or if you are sure the
> thread was not started (due to some error that precludes the call to
> make-thread).

Thanks!  So I could go with something like this:
--8<---------------cut here---------------start------------->8---
(setq-local lexical-binding t)

(defun eli-solution ()
  (interactive)
  (let ((buf (generate-new-buffer "*foo*")))
    (with-current-buffer buf
      (insert "secret message"))
    (let ((cleanup #'(lambda () (kill-buffer buf)))
	  thread)
      (unwind-protect
	  (setf thread (make-thread #'(lambda ()
					(with-current-buffer buf
					  (sit-for 10)
					  (message (buffer-string))
					  (funcall cleanup)))))
	(unless (thread-live-p thread)
	  (funcall cleanup))))))
--8<---------------cut here---------------end--------------->8---

BTW, do you know a more elisp way of defining a function than
"(let ((f #'(lambda…))))" form?
-- 
Manuel Giraud