Function: make-thread

make-thread is a function defined in thread.c.

Signature

(make-thread FUNCTION &optional NAME BUFFER-DISPOSITION)

Documentation

Start a new thread and run FUNCTION in it.

When the function exits, the thread dies. If NAME is given, it must be a string; it names the new thread.

BUFFER-DISPOSITION determines how attached the thread is to its current buffer. If the value is t, that buffer can't be killed. Any other value, including nil (the default), means that if its buffer is killed, the thread is switched to another buffer and receives an error signal thread-buffer-killed. But if the value is symbol silently, no error will be signaled.

View in manual

Probably introduced at or before Emacs version 31.1.

Source Code

// Defined in /usr/src/emacs/src/thread.c
{
  /* Can't start a thread in temacs.  */
  if (!initialized)
    emacs_abort ();

  if (!NILP (name))
    CHECK_STRING (name);

  struct thread_state *new_thread
    = ALLOCATE_ZEROED_PSEUDOVECTOR (struct thread_state, event_object,
				    PVEC_THREAD);
  new_thread->function = function;
  new_thread->name = name;
  /* Perhaps copy m_last_thing_searched from parent?  */
  new_thread->m_current_buffer = current_thread->m_current_buffer;

  ptrdiff_t size = 50;
  union specbinding *pdlvec = xmalloc ((1 + size) * sizeof (union specbinding));
  new_thread->m_specpdl = pdlvec + 1;  /* Skip the dummy entry.  */
  new_thread->m_specpdl_end = new_thread->m_specpdl + size;
  new_thread->m_specpdl_ptr = new_thread->m_specpdl;

  init_bc_thread (&new_thread->bc);

  sys_cond_init (&new_thread->thread_condvar);

  /* We'll need locking here eventually.  */
  new_thread->next_thread = all_threads;
  all_threads = new_thread;

  char const *c_name = !NILP (name) ? SSDATA (ENCODE_SYSTEM (name)) : NULL;
  if (c_name)
    new_thread->thread_name = xstrdup (c_name);
  else
    new_thread->thread_name = NULL;
  sys_thread_t thr;
  if (! sys_thread_create (&thr, run_thread, new_thread))
    {
      /* Restore the previous situation.  */
      all_threads = all_threads->next_thread;
#ifdef THREADS_ENABLED
      error ("Could not start a new thread");
#else
      error ("Concurrency is not supported in this configuration");
#endif
    }

  new_thread->buffer_disposition = buffer_disposition;

  /* FIXME: race here where new thread might not be filled in?  */
  Lisp_Object result;
  XSETTHREAD (result, new_thread);
  return result;
}