Subject: Re: bug#25265: make-thread crashes in OS X 10.6

From: Eli Zaretskii <[email-masked]>
Date: Sat, 31 Dec 2016 11:20:34 +0200

> Date: Fri, 30 Dec 2016 22:05:44 +0000
> From: Alan Third <[email-masked]>
> Cc: [email-masked], [email-masked]
> 
> > > Am I right in thinking that raising SIGIO will cause ns_read_socket to
> > > be potentially run immediately? Asynchronously?
> > 
> > I very much hope not.  We don't run any non-trivial code from a signal
> > handler.  I'd expect SIGIO just to set a flag, and then the resulting
> > input be processed when we call unblock_input next time, and the
> > blocking level gets to zero.  Then we run process_pending_signals,
> > which calls handle_async_input, and that's where ns_read_socket will
> > be called by gobble_input.
> 
> OK. I am, again, none the wiser.

Don't give up ;-)

> > > So, my plan of action:
> > > 
> > > Run [NSApp run] in it’s own thread with no flow control (unless it’s
> > > important that emacs events are only created at specific times?)
> > 
> > How will that thread communicate the events to Emacs?
> 
> I’m hoping using the same method as it does now. It creates emacs
> events from the NS events, and then fires SIGIO.
> 
> I have run into a problem almost right away, though. I don’t know how
> to go about creating this thread.
> 
> The NSApp loop needs to run in the ‘main’ thread on macOS. I
> understand the main thread is always the original thread, so if I want
> to use it for the NSApp loop, I need to move Emacs’ normal operation
> into a child thread.

How about a more modest goal instead?  The code in ns_select can
detect when it is run by the main thread: we have a function,
main_thread_p, for that.  (For it to work, you need to pass
current_thread to it, so we will have to make sure the first part of
ns_select, up to the pselect call, is run with the global lock owned
by a single thread.  The easiest way of achieving that is to do for
ns_select the same change I did yesterday for xg_select: call
ns_select directly in process.c:wait_reading_process_output, then
change ns_select to call thread_select instead of pselect.)

When ns_select detects it's run by a non-main thread, it will only
call thread_select and return its result.  Otherwise, it will call
thread_select with a very small timeout and with NULL descriptor sets
(to let other threads an opportunity to run, and when that returns, do
the [NSApp run] dance with the surrounding code.  Note that the latter
runs after the main thread has re-acquired the global lock, so no
other Lisp threads could be active at that point.

Would that work?

Thanks.