thread.c 9.67 KB
Newer Older
Rafaël Carré's avatar
Rafaël Carré committed
1
2
3
/*****************************************************************************
 * thread.c : android pthread back-end for LibVLC
 *****************************************************************************
4
 * Copyright (C) 1999-2016 VLC authors and VideoLAN
Rafaël Carré's avatar
Rafaël Carré committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 *
 * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
 *          Samuel Hocevar <sam@zoy.org>
 *          Gildas Bazin <gbazin@netcourrier.com>
 *          Clément Sténac
 *          Rémi Denis-Courmont
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <vlc_common.h>
#include <vlc_atomic.h>

#include "libvlc.h"
#include <signal.h>
#include <errno.h>
#include <time.h>
38
#include <assert.h>
Rafaël Carré's avatar
Rafaël Carré committed
39
40
41
42
43
44
45
46
47
48

#include <sys/types.h>
#include <unistd.h> /* fsync() */
#include <pthread.h>
#include <sched.h>

/* debug */

#ifndef NDEBUG
static void
49
50
vlc_thread_fatal_print (const char *action, int error,
                        const char *function, const char *file, unsigned line)
Rafaël Carré's avatar
Rafaël Carré committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
{
    char buf[1000];
    const char *msg;

    switch (strerror_r (error, buf, sizeof (buf)))
    {
        case 0:
            msg = buf;
            break;
        case ERANGE: /* should never happen */
            msg = "unknown (too big to display)";
            break;
        default:
            msg = "unknown (invalid error number)";
            break;
    }

68
69
70
71
    fprintf(stderr, "LibVLC fatal error %s (%d) in thread %lu "
            "at %s:%u in %s\n Error message: %s\n",
            action, error, vlc_thread_id (), file, line, function, msg);
    fflush (stderr);
Rafaël Carré's avatar
Rafaël Carré committed
72
73
}

74
75
76
77
78
79
# define VLC_THREAD_ASSERT( action ) do { \
    if (unlikely(val)) { \
        vlc_thread_fatal_print (action, val, __func__, __FILE__, __LINE__); \
        assert (!action); \
    } \
} while(0)
Rafaël Carré's avatar
Rafaël Carré committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#else
# define VLC_THREAD_ASSERT( action ) ((void)val)
#endif

/* mutexes */
void vlc_mutex_init( vlc_mutex_t *p_mutex )
{
    pthread_mutexattr_t attr;

    pthread_mutexattr_init (&attr);
#ifdef NDEBUG
    pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_DEFAULT);
#else
    pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK);
#endif
    pthread_mutex_init (p_mutex, &attr);
    pthread_mutexattr_destroy( &attr );
}

void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
{
    pthread_mutexattr_t attr;

    pthread_mutexattr_init (&attr);
    pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
    pthread_mutex_init (p_mutex, &attr);
    pthread_mutexattr_destroy( &attr );
}


void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
{
    int val = pthread_mutex_destroy( p_mutex );
    VLC_THREAD_ASSERT ("destroying mutex");
}

#ifndef NDEBUG
void vlc_assert_locked (vlc_mutex_t *p_mutex)
{
119
    assert (pthread_mutex_lock (p_mutex) == EDEADLK);
Rafaël Carré's avatar
Rafaël Carré committed
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
}
#endif

void vlc_mutex_lock (vlc_mutex_t *p_mutex)
{
    int val = pthread_mutex_lock( p_mutex );
    VLC_THREAD_ASSERT ("locking mutex");
}

int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
{
    int val = pthread_mutex_trylock( p_mutex );

    if (val != EBUSY)
        VLC_THREAD_ASSERT ("locking mutex");
    return val;
}

void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
{
    int val = pthread_mutex_unlock( p_mutex );
    VLC_THREAD_ASSERT ("unlocking mutex");
}

struct vlc_thread
{
    pthread_t      thread;
147
    vlc_sem_t      finished;
Rafaël Carré's avatar
Rafaël Carré committed
148
149
150
151

    void *(*entry)(void*);
    void *data;

152
153
154
155
156
157
    struct
    {
        void *addr; /// Non-null if waiting on futex
        vlc_mutex_t lock ; /// Protects futex address
    } wait;

158
    atomic_bool killed;
159
    bool killable;
Rafaël Carré's avatar
Rafaël Carré committed
160
161
162
163
};

static __thread struct vlc_thread *thread = NULL;

164
165
166
167
168
vlc_thread_t vlc_thread_self (void)
{
    return thread;
}

Rafaël Carré's avatar
Rafaël Carré committed
169
170
171
172
173
174
void vlc_threads_setup (libvlc_int_t *p_libvlc)
{
    (void)p_libvlc;
}

/* pthread */
175
176
static void clean_detached_thread(void *data)
{
177
    struct vlc_thread *th = data;
178
179

    /* release thread handle */
180
    vlc_mutex_destroy(&th->wait.lock);
181
    free(th);
182
}
Rafaël Carré's avatar
Rafaël Carré committed
183

184
185
186
187
188
static void *detached_thread(void *data)
{
    vlc_thread_t th = data;

    thread = th;
189

190
    vlc_cleanup_push(clean_detached_thread, th);
191
    th->entry(th->data);
192
    vlc_cleanup_pop();
193
    clean_detached_thread(th);
194
195
196
    return NULL;
}

197
198
199
200
201
202
203
static void finish_joinable_thread(void *data)
{
    vlc_thread_t th = data;

    vlc_sem_post(&th->finished);
}

204
205
206
207
208
static void *joinable_thread(void *data)
{
    vlc_thread_t th = data;
    void *ret;

209
    vlc_cleanup_push(finish_joinable_thread, th);
210
211
    thread = th;
    ret = th->entry(th->data);
212
213
    vlc_cleanup_pop();
    vlc_sem_post(&th->finished);
214

215
216
217
218
219
    return ret;
}

static int vlc_clone_attr (vlc_thread_t *th, void *(*entry) (void *),
                           void *data, bool detach)
Rafaël Carré's avatar
Rafaël Carré committed
220
{
221
222
223
224
    vlc_thread_t thread = malloc (sizeof (*thread));
    if (unlikely(thread == NULL))
        return ENOMEM;

Rafaël Carré's avatar
Rafaël Carré committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    int ret;

    sigset_t oldset;
    {
        sigset_t set;
        sigemptyset (&set);
        sigdelset (&set, SIGHUP);
        sigaddset (&set, SIGINT);
        sigaddset (&set, SIGQUIT);
        sigaddset (&set, SIGTERM);

        sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
        pthread_sigmask (SIG_BLOCK, &set, &oldset);
    }

240
241
    if (!detach)
        vlc_sem_init(&thread->finished, 0);
242
    atomic_store(&thread->killed, false);
243
    thread->killable = true;
Rafaël Carré's avatar
Rafaël Carré committed
244
245
    thread->entry = entry;
    thread->data = data;
246
247
    thread->wait.addr = NULL;
    vlc_mutex_init(&thread->wait.lock);
Rafaël Carré's avatar
Rafaël Carré committed
248

249
250
251
252
253
    pthread_attr_t attr;
    pthread_attr_init (&attr);
    pthread_attr_setdetachstate (&attr, detach ? PTHREAD_CREATE_DETACHED
                                               : PTHREAD_CREATE_JOINABLE);

254
    ret = pthread_create (&thread->thread, &attr,
255
256
                          detach ? detached_thread : joinable_thread, thread);
    pthread_attr_destroy (&attr);
Rafaël Carré's avatar
Rafaël Carré committed
257
258

    pthread_sigmask (SIG_SETMASK, &oldset, NULL);
259
    *th = thread;
Rafaël Carré's avatar
Rafaël Carré committed
260
261
262
263
264
265
    return ret;
}

int vlc_clone (vlc_thread_t *th, void *(*entry) (void *), void *data,
               int priority)
{
266
267
    (void) priority;
    return vlc_clone_attr (th, entry, data, false);
Rafaël Carré's avatar
Rafaël Carré committed
268
269
270
271
}

void vlc_join (vlc_thread_t handle, void **result)
{
272
273
    vlc_sem_wait (&handle->finished);
    vlc_sem_destroy (&handle->finished);
Rafaël Carré's avatar
Rafaël Carré committed
274
275
276

    int val = pthread_join (handle->thread, result);
    VLC_THREAD_ASSERT ("joining thread");
277
    clean_detached_thread(handle);
Rafaël Carré's avatar
Rafaël Carré committed
278
279
280
281
282
283
284
285
286
}

int vlc_clone_detach (vlc_thread_t *th, void *(*entry) (void *), void *data,
                      int priority)
{
    vlc_thread_t dummy;
    if (th == NULL)
        th = &dummy;

287
288
    (void) priority;
    return vlc_clone_attr (th, entry, data, true);
Rafaël Carré's avatar
Rafaël Carré committed
289
290
291
292
293
294
295
296
297
298
}

int vlc_set_priority (vlc_thread_t th, int priority)
{
    (void) th; (void) priority;
    return VLC_SUCCESS;
}

void vlc_cancel (vlc_thread_t thread_id)
{
299
    atomic_int *addr;
300

301
    atomic_store(&thread_id->killed, true);
Rafaël Carré's avatar
Rafaël Carré committed
302

303
304
305
306
    vlc_mutex_lock(&thread_id->wait.lock);
    addr = thread_id->wait.addr;
    if (addr != NULL)
    {
307
        atomic_fetch_or_explicit(addr, 1, memory_order_relaxed);
308
309
310
        vlc_addr_broadcast(addr);
    }
    vlc_mutex_unlock(&thread_id->wait.lock);
Rafaël Carré's avatar
Rafaël Carré committed
311
312
313
314
315
316
317
}

int vlc_savecancel (void)
{
    if (!thread) /* not created by VLC, can't be cancelled */
        return true;

318
    int oldstate = thread->killable;
319
    thread->killable = false;
Rafaël Carré's avatar
Rafaël Carré committed
320
321
322
323
324
325
326
327
    return oldstate;
}

void vlc_restorecancel (int state)
{
    if (!thread) /* not created by VLC, can't be cancelled */
        return;

328
    thread->killable = state;
Rafaël Carré's avatar
Rafaël Carré committed
329
330
331
332
333
334
}

void vlc_testcancel (void)
{
    if (!thread) /* not created by VLC, can't be cancelled */
        return;
335
    if (!thread->killable)
Rafaël Carré's avatar
Rafaël Carré committed
336
        return;
337
    if (!atomic_load(&thread->killed))
Rafaël Carré's avatar
Rafaël Carré committed
338
339
340
341
342
        return;

    pthread_exit(NULL);
}

343
344
345
346
347
void vlc_control_cancel(int cmd, ...)
{
    vlc_thread_t th = vlc_thread_self();
    va_list ap;

348
349
350
    if (th == NULL)
        return;

351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
    va_start(ap, cmd);
    switch (cmd)
    {
        case VLC_CANCEL_ADDR_SET:
        {
            void *addr = va_arg(ap, void *);

            vlc_mutex_lock(&th->wait.lock);
            assert(th->wait.addr == NULL);
            th->wait.addr = addr;
            vlc_mutex_unlock(&th->wait.lock);
            break;
        }

        case VLC_CANCEL_ADDR_CLEAR:
        {
            void *addr = va_arg(ap, void *);

            vlc_mutex_lock(&th->wait.lock);
            assert(th->wait.addr == addr);
            th->wait.addr = NULL;
            (void) addr;
            vlc_mutex_unlock(&th->wait.lock);
            break;
        }

        default:
            vlc_assert_unreachable ();
    }
    va_end(ap);
}

Rafaël Carré's avatar
Rafaël Carré committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/* threadvar */

int vlc_threadvar_create (vlc_threadvar_t *key, void (*destr) (void *))
{
    return pthread_key_create (key, destr);
}

void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
{
    pthread_key_delete (*p_tls);
}

int vlc_threadvar_set (vlc_threadvar_t key, void *value)
{
    return pthread_setspecific (key, value);
}

void *vlc_threadvar_get (vlc_threadvar_t key)
{
    return pthread_getspecific (key);
}

/* time */
mtime_t mdate (void)
{
    struct timespec ts;

410
    if (unlikely(clock_gettime (CLOCK_MONOTONIC, &ts) != 0))
Rafaël Carré's avatar
Rafaël Carré committed
411
412
413
414
415
416
417
418
419
420
421
        abort ();

    return (INT64_C(1000000) * ts.tv_sec) + (ts.tv_nsec / 1000);
}

/* cpu */

unsigned vlc_GetCPUCount(void)
{
    return sysconf(_SC_NPROCESSORS_CONF);
}