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

From: Eli Zaretskii <[email-masked]>
Date: Fri, 30 Dec 2016 23:08:54 +0200

> Date: Fri, 30 Dec 2016 18:45:32 +0000
> From: Alan Third <[email-masked]>
> Cc: [email-masked], [email-masked]
> 
> > > If there’s NS input, it’s processed by the NSApp loop
> > 
> > Processed how?  Shouldn't Emacs be involved in this processing?  IOW,
> > these events should be read by Emacs, via the read_socket_hook.
> 
> Ah! Is this the missing piece of the puzzle? When the [NSApp run] loop
> receives an event, say keyboard input, it creates an emacs_event and
> then raises SIGIO (via hold_event). SIGIO causes ns_read_socket to be
> run, which ALSO tries to run [NSApp run].
> 
> 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.

> I’ve just commented out the section of ns_read_socket that calls
> [NSApp run] and I can’t see any difference in behaviour. I suspect
> that someone’s doubled up on it when they didn’t need to.

I cannot help you here.  Maybe it's needed for Emacs to be more
responsive?  If you run "git log -L" on ns_read_socket, does the
history tell anything about why this call was added?  Perhaps some
discussion or bug report?

> > One possible solution might be to let only one thread, say the main
> > thread, to call [NSApp run].  The other threads, when they get into
> > ns_select, will behave as if Emacs runs in non-GUI mode, and will only
> > call pselect.  Not sure what this will mean from the POV of all
> > threads being equal (since the delicate dance between ns_select and
> > ns_read_socket is still unclear to me), but at least it might avoid
> > crashes and hangs.  Can you try something like that?
> 
> Yes, I will. Am I right in thinking that if we remove all the NSApp
> junk from ns_select it will literally just be calling pselect with
> the same arguments?

It looks like that, yes.

> 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?

> Thanks for helping with this, I don’t think I’d be able to work it out
> on my own.

Thank you for digging into the problem.