VLC 4.0.0-dev
Loading...
Searching...
No Matches
Threads and synchronization primitives
Collaboration diagram for Threads and synchronization primitives:

Modules

 Interruptible sleep
 
 Mutual exclusion locks
 
 Condition variables
 The condition variable is the most common and generic mean for threads to wait for events triggered by other threads.
 
 Semaphores
 The semaphore is the simplest thread synchronization primitive, consisting of a simple counter.
 
 Latches
 The latch is a downward counter used to synchronise threads.
 
 Thread-specific variables
 
 Asynchronous/threaded timers
 

Files

file  vlc_threads.h
 Thread primitive declarations.
 

Data Structures

struct  vlc_thread_t
 Thread handle. More...
 
struct  vlc_once_t
 One-time initialization. More...
 

Macros

#define LIBVLC_USE_PTHREAD   1
 Whether LibVLC threads are based on POSIX threads.
 
#define LIBVLC_USE_PTHREAD_CLEANUP   1
 Whether LibVLC thread cancellation is based on POSIX threads.
 
#define VLC_THREAD_CANCELED   PTHREAD_CANCELED
 Return value of a canceled thread.
 
#define VLC_STATIC_ONCE   { 0 }
 Static initializer for one-time initialization.
 
#define vlc_once_begin(once)   vlc_once_begin_inline(once)
 
#define VLC_HARD_MIN_SLEEP   VLC_TICK_FROM_MS(10) /* 10 milliseconds = 1 tick at 100Hz */
 
#define VLC_SOFT_MIN_SLEEP   VLC_TICK_FROM_SEC(9) /* 9 seconds */
 
#define vlc_cleanup_push(routine, arg)   pthread_cleanup_push (routine, arg)
 Registers a thread cancellation handler.
 
#define vlc_cleanup_pop()   pthread_cleanup_pop (0)
 Unregisters the last cancellation handler.
 
#define vlc_global_lock(n)   vlc_global_mutex(n, true)
 Acquires a global mutex.
 
#define vlc_global_unlock(n)   vlc_global_mutex(n, false)
 Releases a global mutex.
 

Typedefs

typedef struct vlc_cleanup_t vlc_cleanup_t
 

Enumerations

enum  {
  VLC_AVCODEC_MUTEX = 0 , VLC_GCRYPT_MUTEX , VLC_XLIB_MUTEX , VLC_MOSAIC_MUTEX ,
  VLC_MAX_MUTEX
}
 

Functions

void vlc_testcancel (void)
 Issues an explicit deferred cancellation point.
 
bool vlc_once_begin (vlc_once_t *restrict once)
 Begins a one-time initialization.
 
static bool vlc_once_begin_inline (vlc_once_t *restrict once)
 
void vlc_once_complete (vlc_once_t *restrict once)
 Completes a one-time initialization.
 
static void vlc_once (vlc_once_t *restrict once, void(*cb)(void *), void *opaque)
 Executes a function one time.
 
int vlc_clone (vlc_thread_t *th, void *(*entry)(void *), void *data)
 Creates and starts a new thread.
 
void vlc_thread_set_name (const char *name)
 Set the thread name of the current thread.
 
void vlc_cancel (vlc_thread_t)
 Marks a thread as cancelled.
 
void vlc_join (vlc_thread_t th, void **result)
 Waits for a thread to complete (if needed), then destroys it.
 
int vlc_savecancel (void)
 Disables thread cancellation.
 
void vlc_restorecancel (int state)
 Restores the cancellation state.
 
void vlc_control_cancel (vlc_cleanup_t *)
 Internal handler for thread cancellation.
 
unsigned long vlc_thread_id (void)
 Thread identifier.
 
vlc_tick_t vlc_tick_now (void)
 Precision monotonic clock.
 
void vlc_tick_wait (vlc_tick_t deadline)
 Waits until a deadline.
 
void vlc_tick_sleep (vlc_tick_t delay)
 Waits for an interval of time.
 
unsigned vlc_GetCPUCount (void)
 Count CPUs.
 
void vlc_global_mutex (unsigned, bool)
 Internal handler for global mutexes.
 

Detailed Description

Macro Definition Documentation

◆ LIBVLC_USE_PTHREAD

#define LIBVLC_USE_PTHREAD   1

Whether LibVLC threads are based on POSIX threads.

◆ LIBVLC_USE_PTHREAD_CLEANUP

#define LIBVLC_USE_PTHREAD_CLEANUP   1

Whether LibVLC thread cancellation is based on POSIX threads.

◆ vlc_cleanup_pop

#define vlc_cleanup_pop ( )    pthread_cleanup_pop (0)

Unregisters the last cancellation handler.

This pops the cancellation handler that was last pushed with vlc_cleanup_push() in the calling thread.

◆ vlc_cleanup_push

#define vlc_cleanup_push (   routine,
  arg 
)    pthread_cleanup_push (routine, arg)

Registers a thread cancellation handler.

This pushes a function to run if the thread is cancelled (or otherwise exits prematurely).

If multiple procedures are registered, they are handled in last-in first-out order.

Note
Any call to vlc_cleanup_push() must paired with a call to vlc_cleanup_pop().
Warning
Branching into or out of the block between these two function calls is not allowed (read: it will likely crash the whole process).
Parameters
routineprocedure to call if the thread ends
argargument for the procedure

◆ vlc_global_lock

#define vlc_global_lock (   n)    vlc_global_mutex(n, true)

Acquires a global mutex.

◆ vlc_global_unlock

#define vlc_global_unlock (   n)    vlc_global_mutex(n, false)

Releases a global mutex.

◆ VLC_HARD_MIN_SLEEP

#define VLC_HARD_MIN_SLEEP   VLC_TICK_FROM_MS(10) /* 10 milliseconds = 1 tick at 100Hz */

◆ vlc_once_begin

#define vlc_once_begin (   once)    vlc_once_begin_inline(once)

◆ VLC_SOFT_MIN_SLEEP

#define VLC_SOFT_MIN_SLEEP   VLC_TICK_FROM_SEC(9) /* 9 seconds */

◆ VLC_STATIC_ONCE

#define VLC_STATIC_ONCE   { 0 }

Static initializer for one-time initialization.

◆ VLC_THREAD_CANCELED

#define VLC_THREAD_CANCELED   PTHREAD_CANCELED

Return value of a canceled thread.

Typedef Documentation

◆ vlc_cleanup_t

typedef struct vlc_cleanup_t vlc_cleanup_t

Enumeration Type Documentation

◆ anonymous enum

anonymous enum
Enumerator
VLC_AVCODEC_MUTEX 
VLC_GCRYPT_MUTEX 
VLC_XLIB_MUTEX 
VLC_MOSAIC_MUTEX 
VLC_MAX_MUTEX 

Function Documentation

◆ vlc_cancel()

void vlc_cancel ( vlc_thread_t  thread_id)

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 regardless of a thread being cancelled or not, to avoid leaking resources.

References vlc_thread_t::handle, vlc_atomic_notify_one(), and vlc_cancel_self().

Referenced by Close(), httpd_HostDelete(), vlc_getaddrinfo_i11e(), vlc_h2_conn_destroy(), and vlc_h2_output_destroy().

◆ vlc_clone()

int vlc_clone ( vlc_thread_t th,
void *(*)(void *)  entry,
void *  data 
)

Creates and starts a new thread.

The thread must be joined with vlc_join() to reclaim resources when it is not needed anymore.

Parameters
thstorage space for the handle of the new thread (cannot be NULL) [OUT]
entryentry point for the thread
datadata parameter given to the entry point
Returns
0 on success, a standard error code on error.
Note
In case of error, the value of *th is undefined.

References vlc_thread::cancel_event, vlc_thread::cancel_sock, vlc_thread::cleaners, vlc_thread::data, vlc_thread::done_event, vlc_thread::entry, vlc_thread::id, vlc_thread::killable, vlc_thread::killed, vlc_thread::tid, unlikely, vlc_clone_attr(), and vlc_entry().

Referenced by addons_manager_Gather(), decoder_New(), httpd_HostCreate(), input_Start(), InstallEntry(), OpenSDP(), OpenURL(), sout_AnnounceRegisterSDP(), SpawnThread(), spu_Create(), TsStart(), update_Check(), update_Download(), vlc_demux_chained_New(), vlc_getaddrinfo_i11e(), vlc_h2_conn_create(), vlc_h2_output_create(), vlc_mta_acquire(), vlc_player_New(), vlc_timer_create(), vlm_New(), and vout_Request().

◆ vlc_control_cancel()

void vlc_control_cancel ( vlc_cleanup_t cleaner)

Internal handler for thread cancellation.

Do not call this function directly. Use wrapper macros instead: vlc_cleanup_push(), vlc_cleanup_pop().

References vlc_thread::cleaners, current_thread_ctx, and vlc_assert_unreachable.

◆ vlc_GetCPUCount()

unsigned vlc_GetCPUCount ( void  )

Count CPUs.

Returns
number of available (logical) CPUs.

References count, unlikely, and vlc_alloc().

◆ vlc_global_mutex()

void vlc_global_mutex ( unsigned  n,
bool  acquire 
)

Internal handler for global mutexes.

Do not use this function directly. Use helper macros instead: vlc_global_lock(), vlc_global_unlock().

References ARRAY_SIZE, lock, VLC_MAX_MUTEX, vlc_mutex_lock(), vlc_mutex_unlock(), and VLC_STATIC_MUTEX.

◆ vlc_join()

void vlc_join ( vlc_thread_t  th,
void **  result 
)

Waits for a thread to complete (if needed), then destroys it.

Note
This is a cancellation point. In case of cancellation, the thread is not joined.
Warning
A thread cannot join itself (normally VLC will abort if this is attempted).
Parameters
ththread handle
result[OUT] pointer to write the thread return value or NULL

References vlc_thread_t::handle, vlc_testcancel(), VLC_THREAD_ASSERT, and vlc_WaitForSingleObject().

Referenced by addons_manager_Delete(), Close(), httpd_HostDelete(), input_Close(), sout_AnnounceUnRegister(), spu_Destroy(), TsStop(), update_Check(), update_Delete(), update_Download(), vlc_demux_chained_Delete(), vlc_executor_Delete(), vlc_getaddrinfo_i11e(), vlc_h2_conn_destroy(), vlc_h2_output_destroy(), vlc_input_decoder_Delete(), vlc_mta_release(), vlc_player_Delete(), vlc_timer_destroy(), vlm_Delete(), and vout_StopDisplay().

◆ vlc_once()

static void vlc_once ( vlc_once_t *restrict  once,
void(*)(void *)  cb,
void *  opaque 
)
inlinestatic

Executes a function one time.

The first time this function is called with a given one-time initialization object, it executes the provided callback with the provided data pointer as sole parameter. Any further call with the same object will be a no-op.

In the corner case that the first time execution is ongoing in another thread, then the function will wait for completion on the other thread (and then synchronize memory) before it returns. This ensures that, no matter what, the callback has been executed exactly once and its side effects are visible after the function returns.

Parameters
oncea one-time initialization object
cbcallback to execute (the first time)
opaquedata pointer for the callback

References unlikely, vlc_once_begin, and vlc_once_complete().

◆ vlc_once_begin()

bool vlc_once_begin ( vlc_once_t *restrict  once)

Begins a one-time initialization.

This function checks if a one-time initialization has completed:

  • If this is the first time the function is called for the given one-time initialization object, it marks the beginning of the initialization and returns true. vlc_once_complete() must be called to mark the completion of the initialisation.
  • Otherwise, it waits until the initialization completes and returns false.
  • In particular, if the initialization has already completed, the function returns false immediately without actually waiting.

The specified one-time initialization object must have been initialized with VLC_STATIC_ONCE, which is a constant expression suitable as a static initializer.

Warning
If this function is called twice without an intervening call to vlc_once_complete(), a dead lock will occur.
Parameters
onceone-time initialisation object
Return values
falseon the first call (for the given object)
trueon subsequent calls (for the given object)

References unlikely, vlc_cond_waiter::value, vlc_atomic_wait(), VLC_ONCE_CONTEND, VLC_ONCE_DOING, VLC_ONCE_DONE, and VLC_ONCE_UNDONE.

◆ vlc_once_begin_inline()

static bool vlc_once_begin_inline ( vlc_once_t *restrict  once)
inlinestatic

References unlikely, and vlc_once_begin.

◆ vlc_once_complete()

void vlc_once_complete ( vlc_once_t *restrict  once)

Completes a one-time initialization.

This function marks the end of an ongoing one-time initialization. If any thread is waiting for the completion of that initialization, its execution will be resumed.

Warning
The behavior is undefined if the one-time initialization object is uninitialized, if one-time initialization has not started, or if one-time initialization has already completed.
Parameters
onceone-time initialisation object

References vlc_assert_unreachable, vlc_atomic_notify_all(), VLC_ONCE_CONTEND, VLC_ONCE_DOING, and VLC_ONCE_DONE.

Referenced by vlc_CPU_functions_init_once(), vlc_once(), and vlc_timer_create().

◆ vlc_restorecancel()

void vlc_restorecancel ( int  state)

◆ vlc_savecancel()

int vlc_savecancel ( void  )

Disables thread cancellation.

This functions saves the current cancellation state (enabled or disabled), then disables cancellation for the calling thread. It must be called before entering a piece of code that is not cancellation-safe, unless it can be proven that the calling thread will not be cancelled.

Note
This function is not a cancellation point.
Returns
Previous cancellation state (opaque value for vlc_restorecancel()).

References current_thread_ctx, vlc_thread::killable, state, thread, and VLC_THREAD_ASSERT.

Referenced by FinderThread(), httpdLoop(), InstallerThread(), rtp_dgram_thread(), update_CheckReal(), update_DownloadReal(), vlc_h2_output_dequeue(), vlc_h2_recv_thread(), vlc_https_connect_proxy(), vlc_https_recv(), vlc_https_send(), vlc_mutex_lock(), vlc_object_deinit(), vlc_poll_i11e_inner(), vlc_poll_i11e_wake(), vlc_thread_fatal(), vlc_tls_ClientSessionCreate(), vlc_tls_ServerSessionCreate(), vlc_tls_SessionDelete(), and vlc_vaLogCallback().

◆ vlc_testcancel()

void vlc_testcancel ( void  )

Issues an explicit deferred cancellation point.

This has no effects if thread cancellation is disabled. This can be called when there is a rather slow non-sleeping operation. This is also used to force a cancellation point in a function that would otherwise not always be one (block_FifoGet() is an example).

References vlc_thread::cancel_event, vlc_thread::cleaners, current_thread_ctx, vlc_thread::data, vlc_thread::done_event, vlc_thread::killable, vlc_thread::killed, p, thread, vlc_cancel_self(), vlc_docancel(), VLC_THREAD_CANCELED, and vlc_thread_cleanup().

Referenced by net_Read(), net_Write(), vlc_atomic_timedwait(), vlc_atomic_timedwait_daytime(), vlc_atomic_wait(), vlc_fifo_Get(), vlc_frame_File(), vlc_join(), vlc_poll_i11e_inner(), vlc_queue_Dequeue(), vlc_select(), and vlc_tick_wait().

◆ vlc_thread_id()

unsigned long vlc_thread_id ( void  )

Thread identifier.

This function returns a non-zero unique identifier of the calling thread. The identifier cannot change for the entire lifetime of the thread, and two concurrent threads cannot have the same identifier.

The thread identifier has no defined semantics other than uniqueness, and no particular purposes within LibVLC. It is provided mainly for tracing and debugging.

On some but not all supported platforms, the thread identifier is in fact the OS/kernel thread identifier (a.k.a. task PID), and is temporally unique not only within the process but across the entire system.

Note
The main() thread identifier is typically identical to the process identifier, but this is not portable.
Returns
the thread identifier (cannot fail)

References unlikely.

Referenced by vlc_mutex_held(), vlc_mutex_lock(), vlc_mutex_trylock(), vlc_queuedmutex_held(), vlc_queuedmutex_lock(), vlc_thread_fatal(), vlc_thread_fatal_print(), and vlc_vaLog().

◆ vlc_thread_set_name()

void vlc_thread_set_name ( const char *  name)

Set the thread name of the current thread.

Parameters
namethe string to use as the thread name
Note
On Linux the name can be up to 16-byte long, including the terminating nul character. If larger, the name will be truncated.

References name, and VLC_UNUSED.

Referenced by DecoderThread(), FinderThread(), httpd_HostThread(), InstallerThread(), Manage(), MtaMainLoop(), Preparse(), rtp_dgram_thread(), Run(), RunDownloader(), RunnableRun(), RunnableRun(), RunSearchLocal(), RunSearchNetwork(), RunThread(), spu_PrerenderThread(), Thread(), ThreadRun(), TsRun(), update_CheckReal(), update_DownloadReal(), vlc_demux_chained_Thread(), vlc_gai_thread(), vlc_h2_client_output_thread(), vlc_h2_output_thread(), vlc_h2_recv_thread(), vlc_player_destructor_Thread(), and vlc_timer_thread().

◆ vlc_tick_now()

vlc_tick_t vlc_tick_now ( void  )

Precision monotonic clock.

In principles, the clock has a precision of 1 MHz. But the actual resolution may be much lower, especially when it comes to sleeping with vlc_tick_wait() or vlc_tick_sleep(). Most general-purpose operating systems provide a resolution of only 100 to 1000 Hz.

Warning
The origin date (time value "zero") is not specified. It is typically the time the kernel started, but this is platform-dependent. If you need wall clock time, use gettimeofday() instead.
Returns
a timestamp in microseconds.

References freq, lldiv(), mdate_selected, Q2LL, lldiv_t::quot, lldiv_t::rem, unlikely, vlc_tick_from_samples(), vlc_tick_from_sec, and vlc_tick_from_timespec.

Referenced by ClockListenerUpdate(), CmdInitAdd(), CmdInitControl(), CmdInitDel(), CmdInitPrivControl(), CmdInitSend(), Control(), DisplayPicture(), EsOutDecodersStopBuffering(), EsOutGetBuffering(), EsOutVaControlLocked(), httpdLoop(), ImageRead(), Init(), input_rate_Add(), input_thread_Events(), MainLoop(), net_Connect(), OSDWidget(), PreparePicture(), PrerenderPicture(), RenderPicture(), rtp_dgram_thread(), rtp_queue(), rtp_timeout(), RunnableRun(), RunnableRun(), RunThread(), sout_AnnounceRegisterSDP(), sout_ClockMainSetFirstPcr(), spu_PrerenderThread(), spu_PutSubpicture(), stream_GetDelay(), stream_IsDrained(), stream_Silence(), Thread(), TraceRender(), TsStart(), UpdateCurrentPicture(), vlc_aout_stream_Drain(), vlc_aout_stream_Play(), vlc_atomic_timedwait(), vlc_atomic_timedwait(), vlc_demux_chained_Thread(), vlc_input_decoder_AddVoutOverlay(), vlc_msleep_i11e(), vlc_player_DisplayPosition(), vlc_player_GetPosition(), vlc_player_GetTime(), vlc_player_input_HandleState(), vlc_player_input_SeekByPos(), vlc_player_input_SeekByTime(), vlc_player_input_UpdateTime(), vlc_player_WaitRetryDelay(), vlc_tick_sleep(), vlc_tick_wait(), vlc_timer_schedule(), vlc_timer_thread(), vlc_tls_ClientSessionCreate(), vout_chrono_Start(), vout_chrono_Stop(), vout_display_window_MouseEvent(), vout_OSDEpg(), vout_OSDText(), vout_SetInterlacingState(), vout_snapshot_Get(), and VoutSnapshotPip().

◆ vlc_tick_sleep()

void vlc_tick_sleep ( vlc_tick_t  delay)

Waits for an interval of time.

Parameters
delayhow long to wait (in microseconds)
Note
The delay may be exceeded due to OS scheduling.
This function is a cancellation point.

References clock_nanosleep(), vlc_tick_now(), vlc_tick_to_timespec(), and vlc_tick_wait().

Referenced by EsOutDrainDecoder(), and ModuleThread_NewSpuBuffer().

◆ vlc_tick_wait()

void vlc_tick_wait ( vlc_tick_t  deadline)

Waits until a deadline.

Parameters
deadlinetimestamp to wait for (vlc_tick_now())
Note
The deadline may be exceeded due to OS scheduling.
This function is a cancellation point.

References clock_nanosleep(), current_thread_ctx, vlc_thread::killable, vlc_thread::killed, likely, MS_FROM_VLC_TICK, thread, unlikely, vlc_atomic_timedwait(), vlc_clock_prec, vlc_clock_setup_once(), vlc_docancel(), vlc_Sleep(), vlc_testcancel(), VLC_TICK_FROM_MS, vlc_tick_now(), and vlc_tick_to_timespec().

Referenced by vlc_mwait_i11e(), and vlc_tick_sleep().