]> git.sesse.net Git - vlc/blobdiff - src/misc/threads.c
Remove old BeOS thread support
[vlc] / src / misc / threads.c
index 656babcf7f0194a808330f52a619f748ec608a44..98b40553503cace34e9cc8b7291a0395c74f44c4 100644 (file)
@@ -31,6 +31,7 @@
 #include <vlc_common.h>
 
 #include "libvlc.h"
+#include <stdarg.h>
 #include <assert.h>
 #ifdef HAVE_UNISTD_H
 # include <unistd.h>
@@ -51,6 +52,8 @@ static volatile unsigned i_initializations = 0;
 # include <sched.h>
 
 static pthread_mutex_t once_mutex = PTHREAD_MUTEX_INITIALIZER;
+#else
+static vlc_threadvar_t cancel_key;
 #endif
 
 /**
@@ -65,42 +68,54 @@ libvlc_global_data_t *vlc_global( void )
     return p_root;
 }
 
-#ifndef NDEBUG
+#ifdef HAVE_EXECINFO_H
+# include <execinfo.h>
+#endif
+
 /**
- * Object running the current thread
+ * Print a backtrace to the standard error for debugging purpose.
  */
-static vlc_threadvar_t thread_object_key;
-
-vlc_object_t *vlc_threadobj (void)
+void vlc_trace (const char *fn, const char *file, unsigned line)
 {
-    return vlc_threadvar_get (&thread_object_key);
-}
+     fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
+     fflush (stderr); /* needed before switch to low-level I/O */
+#ifdef HAVE_BACKTRACE
+     void *stack[20];
+     int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
+     backtrace_symbols_fd (stack, len, 2);
 #endif
+#ifndef WIN32
+     fsync (2);
+#endif
+}
 
-vlc_threadvar_t msg_context_global_key;
-
-#if defined(LIBVLC_USE_PTHREAD)
 static inline unsigned long vlc_threadid (void)
 {
+#if defined(LIBVLC_USE_PTHREAD)
      union { pthread_t th; unsigned long int i; } v = { };
      v.th = pthread_self ();
      return v.i;
-}
 
-#if defined(HAVE_EXECINFO_H) && defined(HAVE_BACKTRACE)
-# include <execinfo.h>
+#elif defined (WIN32)
+     return GetCurrentThreadId ();
+
+#else
+     return 0;
+
 #endif
+}
 
 /*****************************************************************************
  * vlc_thread_fatal: Report an error from the threading layer
  *****************************************************************************
  * This is mostly meant for debugging.
  *****************************************************************************/
-void vlc_pthread_fatal (const char *action, int error,
+void vlc_thread_fatal (const char *action, int error, const char *function,
                         const char *file, unsigned line)
 {
-    fprintf (stderr, "LibVLC fatal error %s in thread %lu at %s:%u: %d\n",
-             action, vlc_threadid (), file, line, error);
+    fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
+             action, error, vlc_threadid ());
+    vlc_trace (function, file, line);
 
     /* Sometimes strerror_r() crashes too, so make sure we print an error
      * message before we invoke it */
@@ -108,7 +123,7 @@ void vlc_pthread_fatal (const char *action, int error,
     /* Avoid the strerror_r() prototype brain damage in glibc */
     errno = error;
     fprintf (stderr, " Error message: %m at:\n");
-#else
+#elif !defined (WIN32)
     char buf[1000];
     const char *msg;
 
@@ -128,21 +143,21 @@ void vlc_pthread_fatal (const char *action, int error,
 #endif
     fflush (stderr);
 
-#ifdef HAVE_BACKTRACE
-    void *stack[20];
-    int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
-    backtrace_symbols_fd (stack, len, 2);
-#endif
-
     abort ();
 }
-#else
-void vlc_pthread_fatal (const char *action, int error,
-                        const char *file, unsigned line)
+
+/**
+ * Per-thread cancellation data
+ */
+#ifndef LIBVLC_USE_PTHREAD_CANCEL
+typedef struct vlc_cancel_t
 {
-    (void)action; (void)error; (void)file; (void)line;
-    abort();
-}
+    vlc_cleanup_t *cleaners;
+    bool           killable;
+    bool           killed;
+} vlc_cancel_t;
+
+# define VLC_CANCEL_INIT { NULL, false, true }
 #endif
 
 /*****************************************************************************
@@ -173,10 +188,9 @@ int vlc_threads_init( void )
         }
 
         /* We should be safe now. Do all the initialization stuff we want. */
-#ifndef NDEBUG
-        vlc_threadvar_create( &thread_object_key, NULL );
+#ifndef LIBVLC_USE_PTHREAD_CANCEL
+        vlc_threadvar_create( &cancel_key, free );
 #endif
-        vlc_threadvar_create( &msg_context_global_key, msg_StackDestroy );
     }
     i_initializations++;
 
@@ -206,9 +220,8 @@ void vlc_threads_end( void )
     if( i_initializations == 1 )
     {
         vlc_object_release( p_root );
-        vlc_threadvar_delete( &msg_context_global_key );
-#ifndef NDEBUG
-        vlc_threadvar_delete( &thread_object_key );
+#ifndef LIBVLC_USE_PTHREAD
+        vlc_threadvar_delete( &cancel_key );
 #endif
     }
     i_initializations--;
@@ -253,27 +266,6 @@ int vlc_mutex_init( vlc_mutex_t *p_mutex )
     *p_mutex = CreateMutex( 0, FALSE, 0 );
     return (*p_mutex != NULL) ? 0 : ENOMEM;
 
-#elif defined( HAVE_KERNEL_SCHEDULER_H )
-    /* check the arguments and whether it's already been initialized */
-    if( p_mutex == NULL )
-    {
-        return B_BAD_VALUE;
-    }
-
-    if( p_mutex->init == 9999 )
-    {
-        return EALREADY;
-    }
-
-    p_mutex->lock = create_sem( 1, "BeMutex" );
-    if( p_mutex->lock < B_NO_ERROR )
-    {
-        return( -1 );
-    }
-
-    p_mutex->init = 9999;
-    return B_OK;
-
 #endif
 }
 
@@ -324,12 +316,6 @@ void __vlc_mutex_destroy( const char * psz_file, int i_line, vlc_mutex_t *p_mute
 
     CloseHandle( *p_mutex );
 
-#elif defined( HAVE_KERNEL_SCHEDULER_H )
-    if( p_mutex->init == 9999 )
-        delete_sem( p_mutex->lock );
-
-    p_mutex->init = 0;
-
 #endif
 }
 
@@ -367,21 +353,6 @@ int __vlc_cond_init( vlc_cond_t *p_condvar )
                               NULL ); /* unnamed */
     return *p_condvar ? 0 : ENOMEM;
 
-#elif defined( HAVE_KERNEL_SCHEDULER_H )
-    if( !p_condvar )
-    {
-        return B_BAD_VALUE;
-    }
-
-    if( p_condvar->init == 9999 )
-    {
-        return EALREADY;
-    }
-
-    p_condvar->thread = -1;
-    p_condvar->init = 9999;
-    return 0;
-
 #endif
 }
 
@@ -399,9 +370,6 @@ void __vlc_cond_destroy( const char * psz_file, int i_line, vlc_cond_t *p_condva
 
     CloseHandle( *p_condvar );
 
-#elif defined( HAVE_KERNEL_SCHEDULER_H )
-    p_condvar->init = 0;
-
 #endif
 }
 
@@ -442,7 +410,10 @@ void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
 #elif defined (WIN32)
 static unsigned __stdcall vlc_entry (void *data)
 {
+    vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
     vlc_thread_t self = data;
+
+    vlc_threadvar_set (&cancel_key, &cancel_data);
     self->data = self->entry (self->data);
     return 0;
 }
@@ -511,7 +482,7 @@ int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
      * memory leaks and the signal functions not working (see Microsoft
      * Knowledge Base, article 104641) */
     HANDLE hThread;
-    vlc_thread_t th = malloc (sizeof (*p_handle));
+    vlc_thread_t th = malloc (sizeof (*th));
 
     if (th == NULL)
         return ENOMEM;
@@ -527,65 +498,88 @@ int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
 
     if (hThread)
     {
+        /* Thread closes the handle when exiting, duplicate it here
+         * to be on the safe side when joining. */
+        if (!DuplicateHandle (GetCurrentProcess (), hThread,
+                              GetCurrentProcess (), &th->handle, 0, FALSE,
+                              DUPLICATE_SAME_ACCESS))
+        {
+            CloseHandle (hThread);
+            free (th);
+            return ENOMEM;
+        }
+
         ResumeThread (hThread);
-        th->handle = hThread;
         if (priority)
             SetThreadPriority (hThread, priority);
+
         ret = 0;
+        *p_handle = th;
     }
     else
     {
         ret = errno;
         free (th);
-        th = NULL;
     }
-    *p_handle = th;
-
-#elif defined( HAVE_KERNEL_SCHEDULER_H )
-    *p_handle = spawn_thread( entry, psz_name, priority, data );
-    ret = resume_thread( *p_handle );
 
 #endif
     return ret;
 }
 
+#if defined (WIN32)
+/* APC procedure for thread cancellation */
+static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
+{
+    (void)dummy;
+    vlc_control_cancel (VLC_DO_CANCEL);
+}
+#endif
+
+/**
+ * Marks a thread as cancelled. Next time the target thread reaches a
+ * cancellation point (while not having disabled cancellation), it will
+ * run its cancellation cleanup handler, the thread variable destructors, and
+ * terminate. vlc_join() must be used afterward regardless of a thread being
+ * cancelled or not.
+ */
+void vlc_cancel (vlc_thread_t thread_id)
+{
+#if defined (LIBVLC_USE_PTHREAD_CANCEL)
+    pthread_cancel (thread_id);
+#elif defined (WIN32)
+    QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
+#else
+#   warning vlc_cancel is not implemented!
+#endif
+}
+
 /**
  * Waits for a thread to complete (if needed), and destroys it.
+ * This is a cancellation point; in case of cancellation, the join does _not_
+ * occur.
+ *
  * @param handle thread handle
  * @param p_result [OUT] pointer to write the thread return value or NULL
  * @return 0 on success, a standard error code otherwise.
  */
-int vlc_join (vlc_thread_t handle, void **result)
+void vlc_join (vlc_thread_t handle, void **result)
 {
 #if defined( LIBVLC_USE_PTHREAD )
-    return pthread_join (handle, result);
+    int val = pthread_join (handle, result);
+    if (val)
+        vlc_thread_fatal ("joining thread", val, __func__, __FILE__, __LINE__);
 
 #elif defined( UNDER_CE ) || defined( WIN32 )
-    HANDLE hThread;
+    do
+        vlc_testcancel ();
+    while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
+                                                        == WAIT_IO_COMPLETION);
 
-    /*
-    ** object will close its thread handle when destroyed, duplicate it here
-    ** to be on the safe side
-    */
-    if (!DuplicateHandle (GetCurrentProcess (), handle->handle,
-                          GetCurrentProcess(), &hThread, 0, FALSE,
-                          DUPLICATE_SAME_ACCESS))
-        return GetLastError (); /* FIXME: errno */
-
-    WaitForSingleObject (hThread, INFINITE);
-    CloseHandle (hThread);
+    CloseHandle (handle->handle);
     if (result)
         *result = handle->data;
     free (handle);
-    return 0;
-
-#elif defined( HAVE_KERNEL_SCHEDULER_H )
-    int32_t exit_value;
-    ret = (B_OK == wait_for_thread( p_priv->thread_id, &exit_value ));
-    if( !ret && result )
-        *result = (void *)exit_value;
 
-    return ret;
 #endif
 }
 
@@ -602,9 +596,6 @@ static void *thread_entry (void *data)
     void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
 
     free (data);
-#ifndef NDEBUG
-    vlc_threadvar_set (&thread_object_key, obj);
-#endif
     msg_Dbg (obj, "thread started");
     func (obj);
     msg_Dbg (obj, "thread ended");
@@ -735,21 +726,12 @@ int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
 /*****************************************************************************
  * vlc_thread_join: wait until a thread exits, inner version
  *****************************************************************************/
-void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line )
+void __vlc_thread_join( vlc_object_t *p_this )
 {
     vlc_object_internals_t *p_priv = vlc_internals( p_this );
-    int i_ret = 0;
 
 #if defined( LIBVLC_USE_PTHREAD )
-    /* Make sure we do return if we are calling vlc_thread_join()
-     * from the joined thread */
-    if (pthread_equal (pthread_self (), p_priv->thread_id))
-    {
-        msg_Warn (p_this, "joining the active thread (VLC might crash)");
-        i_ret = pthread_detach (p_priv->thread_id);
-    }
-    else
-        i_ret = vlc_join (p_priv->thread_id, NULL);
+    vlc_join (p_priv->thread_id, NULL);
 
 #elif defined( UNDER_CE ) || defined( WIN32 )
     HANDLE hThread;
@@ -765,8 +747,7 @@ void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line
             DUPLICATE_SAME_ACCESS) )
     {
         p_priv->b_thread = false;
-        i_ret = GetLastError();
-        goto error;
+        return; /* We have a problem! */
     }
 
     vlc_join( p_priv->thread_id, NULL );
@@ -796,22 +777,103 @@ void __vlc_thread_join( vlc_object_t *p_this, const char * psz_file, int i_line
                  (double)((user_time%(60*1000000))/1000000.0) );
     }
     CloseHandle( hThread );
-error:
 
 #else
-    i_ret = vlc_join( p_priv->thread_id, NULL );
+    vlc_join( p_priv->thread_id, NULL );
 
 #endif
 
-    if( i_ret )
+    p_priv->b_thread = false;
+}
+
+void vlc_thread_cancel (vlc_object_t *obj)
+{
+    vlc_object_internals_t *priv = vlc_internals (obj);
+
+    if (priv->b_thread)
+        vlc_cancel (priv->thread_id);
+}
+
+void vlc_control_cancel (int cmd, ...)
+{
+    /* NOTE: This function only modifies thread-specific data, so there is no
+     * need to lock anything. */
+#ifdef LIBVLC_USE_PTHREAD_CANCEL
+    (void) cmd;
+    assert (0);
+#else
+    va_list ap;
+
+    va_start (ap, cmd);
+
+    vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
+    if (nfo == NULL)
     {
-        errno = i_ret;
-        msg_Err( p_this, "thread_join(%lu) failed at %s:%d (%m)",
-                         (unsigned long)p_priv->thread_id, psz_file, i_line );
+#ifdef WIN32
+        /* Main thread - cannot be cancelled anyway */
+        return;
+#else
+        nfo = malloc (sizeof (*nfo));
+        if (nfo == NULL)
+            return; /* Uho! Expect problems! */
+        *nfo = VLC_CANCEL_INIT;
+        vlc_threadvar_set (&cancel_key, nfo);
+#endif
     }
-    else
-        msg_Dbg( p_this, "thread %lu joined (%s:%d)",
-                         (unsigned long)p_priv->thread_id, psz_file, i_line );
 
-    p_priv->b_thread = false;
+    switch (cmd)
+    {
+        case VLC_SAVE_CANCEL:
+        {
+            int *p_state = va_arg (ap, int *);
+            *p_state = nfo->killable;
+            nfo->killable = false;
+            break;
+        }
+
+        case VLC_RESTORE_CANCEL:
+        {
+            int state = va_arg (ap, int);
+            nfo->killable = state != 0;
+            break;
+        }
+
+        case VLC_TEST_CANCEL:
+            if (nfo->killable && nfo->killed)
+            {
+                for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
+                     p->proc (p->data);
+                free (nfo);
+#if defined (LIBVLC_USE_PTHREAD)
+                pthread_exit (PTHREAD_CANCELLED);
+#elif defined (WIN32)
+                _endthread ();
+#else
+# error Not implemented!
+#endif
+            }
+            break;
+
+        case VLC_DO_CANCEL:
+            nfo->killed = true;
+            break;
+
+        case VLC_CLEANUP_PUSH:
+        {
+            /* cleaner is a pointer to the caller stack, no need to allocate
+             * and copy anything. As a nice side effect, this cannot fail. */
+            vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
+            cleaner->next = nfo->cleaners;
+            nfo->cleaners = cleaner;
+            break;
+        }
+
+        case VLC_CLEANUP_POP:
+        {
+            nfo->cleaners = nfo->cleaners->next;
+            break;
+        }
+    }
+    va_end (ap);
+#endif
 }