Coverage Report

Created: 2026-05-23 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/glib/glib/gthread.c
Line
Count
Source
1
/* GLIB - Library of useful routines for C programming
2
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3
 *
4
 * gthread.c: MT safety related functions
5
 * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
6
 *                Owen Taylor
7
 *
8
 * SPDX-License-Identifier: LGPL-2.1-or-later
9
 *
10
 * This library is free software; you can redistribute it and/or
11
 * modify it under the terms of the GNU Lesser General Public
12
 * License as published by the Free Software Foundation; either
13
 * version 2.1 of the License, or (at your option) any later version.
14
 *
15
 * This library is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
 * Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General Public
21
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
22
 */
23
24
/* Prelude {{{1 ----------------------------------------------------------- */
25
26
/*
27
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
28
 * file for a list of people on the GLib Team.  See the ChangeLog
29
 * files for a list of changes.  These files are distributed with
30
 * GLib at ftp://ftp.gtk.org/pub/gtk/.
31
 */
32
33
/*
34
 * MT safe
35
 */
36
37
/* implement gthread.h's inline functions */
38
#define G_IMPLEMENT_INLINES 1
39
#define __G_THREAD_C__
40
41
#include "config.h"
42
43
#include "glib-private.h"
44
#include "gthread.h"
45
#include "gthreadprivate.h"
46
47
#include <string.h>
48
49
#ifdef G_OS_UNIX
50
#include <unistd.h>
51
52
#if defined(THREADS_POSIX) && defined(HAVE_PTHREAD_GETAFFINITY_NP)
53
#include <pthread.h>
54
#endif
55
#endif /* G_OS_UNIX */
56
57
#ifndef G_OS_WIN32
58
#include <sys/time.h>
59
#include <time.h>
60
#else
61
#include <windows.h>
62
#endif /* G_OS_WIN32 */
63
64
#ifdef __APPLE__
65
#include <sys/sysctl.h>
66
#endif /*__APPLE__*/
67
68
#include "gslice.h"
69
#include "gstrfuncs.h"
70
#include "gtestutils.h"
71
#include "glib_trace.h"
72
#include "gtrace-private.h"
73
74
/* In order that the API can be defined in one place (this file), the platform
75
 * specific code is moved out into separate files so this one doesn’t turn into
76
 * a massive #ifdef tangle.
77
 *
78
 * To avoid the functions in this file becoming tiny trampolines (`jmp` to the
79
 * relevant `_impl` function only), which would be a performance hit on some
80
 * hot paths, #include the platform specific implementations. They are marked as
81
 * `inline` so should be inlined correctly by the compiler without the need for
82
 * link time optimisation or any fancy tricks.
83
 */
84
static inline void g_mutex_init_impl (GMutex *mutex);
85
static inline void g_mutex_clear_impl (GMutex *mutex);
86
static inline void g_mutex_lock_impl (GMutex *mutex);
87
static inline void g_mutex_unlock_impl (GMutex *mutex);
88
static inline gboolean g_mutex_trylock_impl (GMutex *mutex);
89
90
static inline void g_rec_mutex_init_impl (GRecMutex *rec_mutex);
91
static inline void g_rec_mutex_clear_impl (GRecMutex *rec_mutex);
92
static inline void g_rec_mutex_lock_impl (GRecMutex *mutex);
93
static inline void g_rec_mutex_unlock_impl (GRecMutex *rec_mutex);
94
static inline gboolean g_rec_mutex_trylock_impl (GRecMutex *rec_mutex);
95
96
static inline void g_rw_lock_init_impl (GRWLock *rw_lock);
97
static inline void g_rw_lock_clear_impl (GRWLock *rw_lock);
98
static inline void g_rw_lock_writer_lock_impl (GRWLock *rw_lock);
99
static inline gboolean g_rw_lock_writer_trylock_impl (GRWLock *rw_lock);
100
static inline void g_rw_lock_writer_unlock_impl (GRWLock *rw_lock);
101
static inline void g_rw_lock_reader_lock_impl (GRWLock *rw_lock);
102
static inline gboolean g_rw_lock_reader_trylock_impl (GRWLock *rw_lock);
103
static inline void g_rw_lock_reader_unlock_impl (GRWLock *rw_lock);
104
105
static inline void g_cond_init_impl (GCond *cond);
106
static inline void g_cond_clear_impl (GCond *cond);
107
static inline void g_cond_wait_impl (GCond  *cond,
108
                                     GMutex *mutex);
109
static inline void g_cond_signal_impl (GCond *cond);
110
static inline void g_cond_broadcast_impl (GCond *cond);
111
static inline gboolean g_cond_wait_until_impl (GCond  *cond,
112
                                               GMutex *mutex,
113
                                               gint64  end_time);
114
115
static inline gpointer g_private_get_impl (GPrivate *key);
116
static inline void g_private_set_impl (GPrivate *key,
117
                                       gpointer  value);
118
static inline void g_private_replace_impl (GPrivate *key,
119
                                           gpointer  value);
120
121
static inline void g_thread_yield_impl (void);
122
123
#if defined(THREADS_POSIX)
124
#include "gthread-posix.c"
125
#elif defined(THREADS_WIN32)
126
#include "gthread-win32.c"
127
#else
128
#error "No threads implementation"
129
#endif
130
131
/* G_LOCK Documentation {{{1 ---------------------------------------------- */
132
133
/**
134
 * G_LOCK_DEFINE:
135
 * @name: the name of the lock
136
 *
137
 * The `G_LOCK_` macros provide a convenient interface to #GMutex.
138
 * %G_LOCK_DEFINE defines a lock. It can appear in any place where
139
 * variable definitions may appear in programs, i.e. in the first block
140
 * of a function or outside of functions. The @name parameter will be
141
 * mangled to get the name of the #GMutex. This means that you
142
 * can use names of existing variables as the parameter - e.g. the name
143
 * of the variable you intend to protect with the lock. Look at our
144
 * give_me_next_number() example using the `G_LOCK` macros:
145
 *
146
 * Here is an example for using the `G_LOCK` convenience macros:
147
 *
148
 * |[<!-- language="C" --> 
149
 *   G_LOCK_DEFINE (current_number);
150
 *
151
 *   int
152
 *   give_me_next_number (void)
153
 *   {
154
 *     static int current_number = 0;
155
 *     int ret_val;
156
 *
157
 *     G_LOCK (current_number);
158
 *     ret_val = current_number = calc_next_number (current_number);
159
 *     G_UNLOCK (current_number);
160
 *
161
 *     return ret_val;
162
 *   }
163
 * ]|
164
 */
165
166
/**
167
 * G_LOCK_DEFINE_STATIC:
168
 * @name: the name of the lock
169
 *
170
 * This works like %G_LOCK_DEFINE, but it creates a static object.
171
 */
172
173
/**
174
 * G_LOCK_EXTERN:
175
 * @name: the name of the lock
176
 *
177
 * This declares a lock, that is defined with %G_LOCK_DEFINE in another
178
 * module.
179
 */
180
181
/**
182
 * G_LOCK:
183
 * @name: the name of the lock
184
 *
185
 * Works like g_mutex_lock(), but for a lock defined with
186
 * %G_LOCK_DEFINE.
187
 */
188
189
/**
190
 * G_TRYLOCK:
191
 * @name: the name of the lock
192
 *
193
 * Works like g_mutex_trylock(), but for a lock defined with
194
 * %G_LOCK_DEFINE.
195
 *
196
 * Returns: %TRUE, if the lock could be locked.
197
 */
198
199
/**
200
 * G_UNLOCK:
201
 * @name: the name of the lock
202
 *
203
 * Works like g_mutex_unlock(), but for a lock defined with
204
 * %G_LOCK_DEFINE.
205
 */
206
207
/**
208
 * G_AUTO_LOCK:
209
 * @name: the name of the lock
210
 *
211
 * Works like [func@GLib.MUTEX_AUTO_LOCK], but for a lock defined with
212
 * [func@GLib.LOCK_DEFINE].
213
 *
214
 * This feature is only supported on GCC and clang. This macro is not defined on
215
 * other compilers and should not be used in programs that are intended to be
216
 * portable to those compilers.
217
 *
218
 * Since: 2.80
219
 */
220
221
/* GMutex Documentation {{{1 ------------------------------------------ */
222
223
/**
224
 * GMutex:
225
 *
226
 * The #GMutex struct is an opaque data structure to represent a mutex
227
 * (mutual exclusion). It can be used to protect data against shared
228
 * access.
229
 *
230
 * Take for example the following function:
231
 * |[<!-- language="C" --> 
232
 *   int
233
 *   give_me_next_number (void)
234
 *   {
235
 *     static int current_number = 0;
236
 *
237
 *     // now do a very complicated calculation to calculate the new
238
 *     // number, this might for example be a random number generator
239
 *     current_number = calc_next_number (current_number);
240
 *
241
 *     return current_number;
242
 *   }
243
 * ]|
244
 * It is easy to see that this won't work in a multi-threaded
245
 * application. There current_number must be protected against shared
246
 * access. A #GMutex can be used as a solution to this problem:
247
 * |[<!-- language="C" --> 
248
 *   int
249
 *   give_me_next_number (void)
250
 *   {
251
 *     static GMutex mutex;
252
 *     static int current_number = 0;
253
 *     int ret_val;
254
 *
255
 *     g_mutex_lock (&mutex);
256
 *     ret_val = current_number = calc_next_number (current_number);
257
 *     g_mutex_unlock (&mutex);
258
 *
259
 *     return ret_val;
260
 *   }
261
 * ]|
262
 * Notice that the #GMutex is not initialised to any particular value.
263
 * Its placement in static storage ensures that it will be initialised
264
 * to all-zeros, which is appropriate.
265
 *
266
 * If a #GMutex is placed in other contexts (eg: embedded in a struct)
267
 * then it must be explicitly initialised using g_mutex_init().
268
 *
269
 * A #GMutex should only be accessed via g_mutex_ functions.
270
 */
271
272
/* GRecMutex Documentation {{{1 -------------------------------------- */
273
274
/**
275
 * GRecMutex:
276
 *
277
 * The GRecMutex struct is an opaque data structure to represent a
278
 * recursive mutex. It is similar to a #GMutex with the difference
279
 * that it is possible to lock a GRecMutex multiple times in the same
280
 * thread without deadlock. When doing so, care has to be taken to
281
 * unlock the recursive mutex as often as it has been locked.
282
 *
283
 * If a #GRecMutex is allocated in static storage then it can be used
284
 * without initialisation.  Otherwise, you should call
285
 * g_rec_mutex_init() on it and g_rec_mutex_clear() when done.
286
 *
287
 * A GRecMutex should only be accessed with the
288
 * g_rec_mutex_ functions.
289
 *
290
 * Since: 2.32
291
 */
292
293
/* GRWLock Documentation {{{1 ---------------------------------------- */
294
295
/**
296
 * GRWLock:
297
 *
298
 * The GRWLock struct is an opaque data structure to represent a
299
 * reader-writer lock. It is similar to a #GMutex in that it allows
300
 * multiple threads to coordinate access to a shared resource.
301
 *
302
 * The difference to a mutex is that a reader-writer lock discriminates
303
 * between read-only ('reader') and full ('writer') access. While only
304
 * one thread at a time is allowed write access (by holding the 'writer'
305
 * lock via g_rw_lock_writer_lock()), multiple threads can gain
306
 * simultaneous read-only access (by holding the 'reader' lock via
307
 * g_rw_lock_reader_lock()).
308
 *
309
 * It is unspecified whether readers or writers have priority in acquiring the
310
 * lock when a reader already holds the lock and a writer is queued to acquire
311
 * it.
312
 *
313
 * Here is an example for an array with access functions:
314
 * |[<!-- language="C" --> 
315
 *   GRWLock lock;
316
 *   GPtrArray *array;
317
 *
318
 *   gpointer
319
 *   my_array_get (guint index)
320
 *   {
321
 *     gpointer retval = NULL;
322
 *
323
 *     if (!array)
324
 *       return NULL;
325
 *
326
 *     g_rw_lock_reader_lock (&lock);
327
 *     if (index < array->len)
328
 *       retval = g_ptr_array_index (array, index);
329
 *     g_rw_lock_reader_unlock (&lock);
330
 *
331
 *     return retval;
332
 *   }
333
 *
334
 *   void
335
 *   my_array_set (guint index, gpointer data)
336
 *   {
337
 *     g_rw_lock_writer_lock (&lock);
338
 *
339
 *     if (!array)
340
 *       array = g_ptr_array_new ();
341
 *
342
 *     if (index >= array->len)
343
 *       g_ptr_array_set_size (array, index+1);
344
 *     g_ptr_array_index (array, index) = data;
345
 *
346
 *     g_rw_lock_writer_unlock (&lock);
347
 *   }
348
 *  ]|
349
 * This example shows an array which can be accessed by many readers
350
 * (the my_array_get() function) simultaneously, whereas the writers
351
 * (the my_array_set() function) will only be allowed one at a time
352
 * and only if no readers currently access the array. This is because
353
 * of the potentially dangerous resizing of the array. Using these
354
 * functions is fully multi-thread safe now.
355
 *
356
 * If a #GRWLock is allocated in static storage then it can be used
357
 * without initialisation.  Otherwise, you should call
358
 * g_rw_lock_init() on it and g_rw_lock_clear() when done.
359
 *
360
 * A GRWLock should only be accessed with the g_rw_lock_ functions.
361
 *
362
 * Since: 2.32
363
 */
364
365
/* GCond Documentation {{{1 ------------------------------------------ */
366
367
/**
368
 * GCond:
369
 *
370
 * The #GCond struct is an opaque data structure that represents a
371
 * condition. Threads can block on a #GCond if they find a certain
372
 * condition to be false. If other threads change the state of this
373
 * condition they signal the #GCond, and that causes the waiting
374
 * threads to be woken up.
375
 *
376
 * Consider the following example of a shared variable.  One or more
377
 * threads can wait for data to be published to the variable and when
378
 * another thread publishes the data, it can signal one of the waiting
379
 * threads to wake up to collect the data.
380
 *
381
 * Here is an example for using GCond to block a thread until a condition
382
 * is satisfied:
383
 * |[<!-- language="C" --> 
384
 *   gpointer current_data = NULL;
385
 *   GMutex data_mutex;
386
 *   GCond data_cond;
387
 *
388
 *   void
389
 *   push_data (gpointer data)
390
 *   {
391
 *     g_mutex_lock (&data_mutex);
392
 *     current_data = data;
393
 *     g_cond_signal (&data_cond);
394
 *     g_mutex_unlock (&data_mutex);
395
 *   }
396
 *
397
 *   gpointer
398
 *   pop_data (void)
399
 *   {
400
 *     gpointer data;
401
 *
402
 *     g_mutex_lock (&data_mutex);
403
 *     while (!current_data)
404
 *       g_cond_wait (&data_cond, &data_mutex);
405
 *     data = current_data;
406
 *     current_data = NULL;
407
 *     g_mutex_unlock (&data_mutex);
408
 *
409
 *     return data;
410
 *   }
411
 * ]|
412
 * Whenever a thread calls pop_data() now, it will wait until
413
 * current_data is non-%NULL, i.e. until some other thread
414
 * has called push_data().
415
 *
416
 * The example shows that use of a condition variable must always be
417
 * paired with a mutex.  Without the use of a mutex, there would be a
418
 * race between the check of @current_data by the while loop in
419
 * pop_data() and waiting. Specifically, another thread could set
420
 * @current_data after the check, and signal the cond (with nobody
421
 * waiting on it) before the first thread goes to sleep. #GCond is
422
 * specifically useful for its ability to release the mutex and go
423
 * to sleep atomically.
424
 *
425
 * It is also important to use the g_cond_wait() and g_cond_wait_until()
426
 * functions only inside a loop which checks for the condition to be
427
 * true.  See g_cond_wait() for an explanation of why the condition may
428
 * not be true even after it returns.
429
 *
430
 * If a #GCond is allocated in static storage then it can be used
431
 * without initialisation.  Otherwise, you should call g_cond_init()
432
 * on it and g_cond_clear() when done.
433
 *
434
 * A #GCond should only be accessed via the g_cond_ functions.
435
 */
436
437
/* GThread Documentation {{{1 ---------------------------------------- */
438
439
/**
440
 * GThread:
441
 *
442
 * The #GThread struct represents a running thread. This struct
443
 * is returned by g_thread_new() or g_thread_try_new(). You can
444
 * obtain the #GThread struct representing the current thread by
445
 * calling g_thread_self().
446
 *
447
 * GThread is refcounted, see g_thread_ref() and g_thread_unref().
448
 * The thread represented by it holds a reference while it is running,
449
 * and g_thread_join() consumes the reference that it is given, so
450
 * it is normally not necessary to manage GThread references
451
 * explicitly.
452
 *
453
 * The structure is opaque -- none of its fields may be directly
454
 * accessed.
455
 */
456
457
/**
458
 * GThreadFunc:
459
 * @data: data passed to the thread
460
 *
461
 * Specifies the type of the @func functions passed to g_thread_new()
462
 * or g_thread_try_new().
463
 *
464
 * Returns: the return value of the thread
465
 */
466
467
/**
468
 * g_thread_supported:
469
 *
470
 * This macro returns %TRUE if the thread system is initialized,
471
 * and %FALSE if it is not.
472
 *
473
 * For language bindings, g_thread_get_initialized() provides
474
 * the same functionality as a function.
475
 *
476
 * Returns: %TRUE, if the thread system is initialized
477
 */
478
479
/* GThreadError {{{1 ------------------------------------------------------- */
480
/**
481
 * GThreadError:
482
 * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
483
 *                        shortage. Try again later.
484
 *
485
 * Possible errors of thread related functions.
486
 **/
487
488
/**
489
 * G_THREAD_ERROR:
490
 *
491
 * The error domain of the GLib thread subsystem.
492
 **/
493
G_DEFINE_QUARK (g_thread_error, g_thread_error)
494
495
/* Local Data {{{1 -------------------------------------------------------- */
496
497
static GMutex    g_once_mutex;
498
static GCond     g_once_cond;
499
static GSList   *g_once_init_list = NULL;
500
501
static guint g_thread_n_created_counter = 0;  /* (atomic) */
502
503
static void g_thread_cleanup (gpointer data);
504
static GPrivate     g_thread_specific_private = G_PRIVATE_INIT (g_thread_cleanup);
505
506
/*
507
 * g_private_set_alloc0:
508
 * @key: a #GPrivate
509
 * @size: size of the allocation, in bytes
510
 *
511
 * Sets the thread local variable @key to have a newly-allocated and zero-filled
512
 * value of given @size, and returns a pointer to that memory. Allocations made
513
 * using this API will be suppressed in valgrind (when the GLib default
514
 * suppression file, `glib.supp`, is used) and leak sanitizer: it is intended to
515
 * be used for one-time allocations which are known to be leaked, such as those
516
 * for per-thread initialisation data. Otherwise, this function behaves the same
517
 * as g_private_set().
518
 *
519
 * Returns: (transfer full): new thread-local heap allocation of size @size
520
 * Since: 2.60
521
 */
522
/*< private >*/
523
gpointer
524
g_private_set_alloc0 (GPrivate *key,
525
                      gsize     size)
526
0
{
527
0
  gpointer allocated = g_malloc0 (size);
528
529
0
  g_ignore_leak (allocated);
530
0
  g_private_set (key, allocated);
531
532
0
  return g_steal_pointer (&allocated);
533
0
}
534
535
/* GOnce {{{1 ------------------------------------------------------------- */
536
537
/**
538
 * GOnce:
539
 * @status: the status of the #GOnce
540
 * @retval: the value returned by the call to the function, if @status
541
 *          is %G_ONCE_STATUS_READY
542
 *
543
 * A #GOnce struct controls a one-time initialization function. Any
544
 * one-time initialization function must have its own unique #GOnce
545
 * struct.
546
 *
547
 * Since: 2.4
548
 */
549
550
/**
551
 * G_ONCE_INIT:
552
 *
553
 * A #GOnce must be initialized with this macro before it can be used.
554
 *
555
 * |[<!-- language="C" --> 
556
 *   GOnce my_once = G_ONCE_INIT;
557
 * ]|
558
 *
559
 * Since: 2.4
560
 */
561
562
/**
563
 * GOnceStatus:
564
 * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
565
 * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
566
 * @G_ONCE_STATUS_READY: the function has been called.
567
 *
568
 * The possible statuses of a one-time initialization function
569
 * controlled by a #GOnce struct.
570
 *
571
 * Since: 2.4
572
 */
573
574
/**
575
 * g_once:
576
 * @once: a #GOnce structure
577
 * @func: the #GThreadFunc function associated to @once. This function
578
 *        is called only once, regardless of the number of times it and
579
 *        its associated #GOnce struct are passed to g_once().
580
 * @arg: data to be passed to @func
581
 *
582
 * The first call to this routine by a process with a given #GOnce
583
 * struct calls @func with the given argument. Thereafter, subsequent
584
 * calls to g_once()  with the same #GOnce struct do not call @func
585
 * again, but return the stored result of the first call. On return
586
 * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
587
 *
588
 * For example, a mutex or a thread-specific data key must be created
589
 * exactly once. In a threaded environment, calling g_once() ensures
590
 * that the initialization is serialized across multiple threads.
591
 *
592
 * Calling g_once() recursively on the same #GOnce struct in
593
 * @func will lead to a deadlock.
594
 *
595
 * |[<!-- language="C" --> 
596
 *   gpointer
597
 *   get_debug_flags (void)
598
 *   {
599
 *     static GOnce my_once = G_ONCE_INIT;
600
 *
601
 *     g_once (&my_once, parse_debug_flags, NULL);
602
 *
603
 *     return my_once.retval;
604
 *   }
605
 * ]|
606
 *
607
 * Since: 2.4
608
 */
609
gpointer
610
g_once_impl (GOnce       *once,
611
       GThreadFunc  func,
612
       gpointer     arg)
613
0
{
614
0
  g_mutex_lock (&g_once_mutex);
615
616
0
  while (once->status == G_ONCE_STATUS_PROGRESS)
617
0
    g_cond_wait (&g_once_cond, &g_once_mutex);
618
619
0
  if (once->status != G_ONCE_STATUS_READY)
620
0
    {
621
0
      gpointer retval;
622
623
0
      once->status = G_ONCE_STATUS_PROGRESS;
624
0
      g_mutex_unlock (&g_once_mutex);
625
626
0
      retval = func (arg);
627
628
0
      g_mutex_lock (&g_once_mutex);
629
/* We prefer the new C11-style atomic extension of GCC if available. If not,
630
 * fall back to always locking. */
631
0
#if defined(G_ATOMIC_LOCK_FREE) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) && defined(__ATOMIC_SEQ_CST)
632
      /* Only the second store needs to be atomic, as the two writes are related
633
       * by a happens-before relationship here. */
634
0
      once->retval = retval;
635
0
      __atomic_store_n (&once->status, G_ONCE_STATUS_READY, __ATOMIC_RELEASE);
636
#else
637
      once->retval = retval;
638
      once->status = G_ONCE_STATUS_READY;
639
#endif
640
0
      g_cond_broadcast (&g_once_cond);
641
0
    }
642
643
0
  g_mutex_unlock (&g_once_mutex);
644
645
0
  return once->retval;
646
0
}
647
648
/**
649
 * g_once_init_enter:
650
 * @location: (inout) (not optional): location of a static initializable variable
651
 *    containing 0
652
 *
653
 * Function to be called when starting a critical initialization
654
 * section. The argument @location must point to a static
655
 * 0-initialized variable that will be set to a value other than 0 at
656
 * the end of the initialization section. In combination with
657
 * g_once_init_leave() and the unique address @value_location, it can
658
 * be ensured that an initialization section will be executed only once
659
 * during a program's life time, and that concurrent threads are
660
 * blocked until initialization completed. To be used in constructs
661
 * like this:
662
 *
663
 * |[<!-- language="C" --> 
664
 *   static gsize initialization_value = 0;
665
 *
666
 *   if (g_once_init_enter (&initialization_value))
667
 *     {
668
 *       gsize setup_value = 42; // initialization code here
669
 *
670
 *       g_once_init_leave (&initialization_value, setup_value);
671
 *     }
672
 *
673
 *   // use initialization_value here
674
 * ]|
675
 *
676
 * While @location has a `volatile` qualifier, this is a historical artifact and
677
 * the pointer passed to it should not be `volatile`.
678
 *
679
 * Returns: %TRUE if the initialization section should be entered,
680
 *     %FALSE and blocks otherwise
681
 *
682
 * Since: 2.14
683
 */
684
gboolean
685
(g_once_init_enter) (volatile void *location)
686
6
{
687
6
  gsize *value_location = (gsize *) location;
688
6
  gboolean need_init = FALSE;
689
6
  g_mutex_lock (&g_once_mutex);
690
6
  if (g_atomic_pointer_get (value_location) == 0)
691
6
    {
692
6
      if (!g_slist_find (g_once_init_list, (void*) value_location))
693
6
        {
694
6
          need_init = TRUE;
695
6
          g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
696
6
        }
697
0
      else
698
0
        do
699
0
          g_cond_wait (&g_once_cond, &g_once_mutex);
700
0
        while (g_slist_find (g_once_init_list, (void*) value_location));
701
6
    }
702
6
  g_mutex_unlock (&g_once_mutex);
703
6
  return need_init;
704
6
}
705
706
/**
707
 * g_once_init_enter_pointer:
708
 * @location: (not nullable): location of a static initializable variable
709
 *    containing `NULL`
710
 *
711
 * This functions behaves in the same way as g_once_init_enter(), but can
712
 * can be used to initialize pointers (or #guintptr) instead of #gsize.
713
 *
714
 * |[<!-- language="C" -->
715
 *   static MyStruct *interesting_struct = NULL;
716
 *
717
 *   if (g_once_init_enter_pointer (&interesting_struct))
718
 *     {
719
 *       MyStruct *setup_value = allocate_my_struct (); // initialization code here
720
 *
721
 *       g_once_init_leave_pointer (&interesting_struct, g_steal_pointer (&setup_value));
722
 *     }
723
 *
724
 *   // use interesting_struct here
725
 * ]|
726
 *
727
 * Returns: %TRUE if the initialization section should be entered,
728
 *     %FALSE and blocks otherwise
729
 *
730
 * Since: 2.80
731
 */
732
gboolean
733
(g_once_init_enter_pointer) (gpointer location)
734
8
{
735
8
  gpointer *value_location = (gpointer *) location;
736
8
  gboolean need_init = FALSE;
737
8
  g_mutex_lock (&g_once_mutex);
738
8
  if (g_atomic_pointer_get (value_location) == 0)
739
8
    {
740
8
      if (!g_slist_find (g_once_init_list, (void *) value_location))
741
8
        {
742
8
          need_init = TRUE;
743
8
          g_once_init_list = g_slist_prepend (g_once_init_list, (void *) value_location);
744
8
        }
745
0
      else
746
0
        do
747
0
          g_cond_wait (&g_once_cond, &g_once_mutex);
748
0
        while (g_slist_find (g_once_init_list, (void *) value_location));
749
8
    }
750
8
  g_mutex_unlock (&g_once_mutex);
751
8
  return need_init;
752
8
}
753
754
/**
755
 * g_once_init_leave:
756
 * @location: (inout) (not optional): location of a static initializable variable
757
 *    containing 0
758
 * @result: new non-0 value for `*value_location`
759
 *
760
 * Counterpart to g_once_init_enter(). Expects a location of a static
761
 * 0-initialized initialization variable, and an initialization value
762
 * other than 0. Sets the variable to the initialization value, and
763
 * releases concurrent threads blocking in g_once_init_enter() on this
764
 * initialization variable.
765
 *
766
 * While @location has a `volatile` qualifier, this is a historical artifact and
767
 * the pointer passed to it should not be `volatile`.
768
 *
769
 * Since: 2.14
770
 */
771
void
772
(g_once_init_leave) (volatile void *location,
773
                     gsize          result)
774
6
{
775
6
  gsize *value_location = (gsize *) location;
776
6
  gsize old_value;
777
778
6
  g_return_if_fail (result != 0);
779
780
6
  old_value = (gsize) g_atomic_pointer_exchange (value_location, result);
781
6
  g_return_if_fail (old_value == 0);
782
783
6
  g_mutex_lock (&g_once_mutex);
784
6
  g_return_if_fail (g_once_init_list != NULL);
785
6
  g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
786
6
  g_cond_broadcast (&g_once_cond);
787
6
  g_mutex_unlock (&g_once_mutex);
788
6
}
789
790
/**
791
 * g_once_init_leave_pointer:
792
 * @location: (not nullable): location of a static initializable variable
793
 *    containing `NULL`
794
 * @result: new non-`NULL` value for `*location`
795
 *
796
 * Counterpart to g_once_init_enter_pointer(). Expects a location of a static
797
 * `NULL`-initialized initialization variable, and an initialization value
798
 * other than `NULL`. Sets the variable to the initialization value, and
799
 * releases concurrent threads blocking in g_once_init_enter_pointer() on this
800
 * initialization variable.
801
 *
802
 * This functions behaves in the same way as g_once_init_leave(), but
803
 * can be used to initialize pointers (or #guintptr) instead of #gsize.
804
 *
805
 * Since: 2.80
806
 */
807
void
808
(g_once_init_leave_pointer) (gpointer location,
809
                             gpointer result)
810
8
{
811
8
  gpointer *value_location = (gpointer *) location;
812
8
  gpointer old_value;
813
814
8
  g_return_if_fail (result != 0);
815
816
8
  old_value = g_atomic_pointer_exchange (value_location, result);
817
8
  g_return_if_fail (old_value == 0);
818
819
8
  g_mutex_lock (&g_once_mutex);
820
8
  g_return_if_fail (g_once_init_list != NULL);
821
8
  g_once_init_list = g_slist_remove (g_once_init_list, (void *) value_location);
822
8
  g_cond_broadcast (&g_once_cond);
823
8
  g_mutex_unlock (&g_once_mutex);
824
8
}
825
826
/* GThread {{{1 -------------------------------------------------------- */
827
828
/**
829
 * g_thread_ref:
830
 * @thread: a #GThread
831
 *
832
 * Increase the reference count on @thread.
833
 *
834
 * Returns: (transfer full): a new reference to @thread
835
 *
836
 * Since: 2.32
837
 */
838
GThread *
839
g_thread_ref (GThread *thread)
840
0
{
841
0
  GRealThread *real = (GRealThread *) thread;
842
843
0
  g_atomic_int_inc (&real->ref_count);
844
845
0
  return thread;
846
0
}
847
848
/**
849
 * g_thread_unref:
850
 * @thread: (transfer full): a #GThread
851
 *
852
 * Decrease the reference count on @thread, possibly freeing all
853
 * resources associated with it.
854
 *
855
 * Note that each thread holds a reference to its #GThread while
856
 * it is running, so it is safe to drop your own reference to it
857
 * if you don't need it anymore.
858
 *
859
 * Since: 2.32
860
 */
861
void
862
g_thread_unref (GThread *thread)
863
0
{
864
0
  GRealThread *real = (GRealThread *) thread;
865
866
0
  if (g_atomic_int_dec_and_test (&real->ref_count))
867
0
    {
868
0
      if (real->ours)
869
0
        g_system_thread_free (real);
870
0
      else
871
0
        g_slice_free (GRealThread, real);
872
0
    }
873
0
}
874
875
static void
876
g_thread_cleanup (gpointer data)
877
0
{
878
0
  g_thread_unref (data);
879
0
}
880
881
gpointer
882
g_thread_proxy (gpointer data)
883
0
{
884
0
  GRealThread* thread = data;
885
886
0
  g_assert (data);
887
0
  g_private_set (&g_thread_specific_private, data);
888
889
0
  TRACE (GLIB_THREAD_SPAWNED (thread->thread.func, thread->thread.data,
890
0
                              thread->name));
891
892
0
  if (thread->name[0] != '\0')
893
0
    g_system_thread_set_name (thread->name);
894
0
  else
895
0
    g_system_thread_get_name (thread->name, sizeof (thread->name));
896
897
0
  thread->retval = thread->thread.func (thread->thread.data);
898
899
0
  return NULL;
900
0
}
901
902
guint
903
g_thread_n_created (void)
904
0
{
905
0
  return g_atomic_int_get (&g_thread_n_created_counter);
906
0
}
907
908
/**
909
 * g_thread_new:
910
 * @name: (nullable): an (optional) name for the new thread
911
 * @func: (closure data) (scope async): a function to execute in the new thread
912
 * @data: (nullable): an argument to supply to the new thread
913
 *
914
 * This function creates a new thread. The new thread starts by invoking
915
 * @func with the argument data. The thread will run until @func returns
916
 * or until g_thread_exit() is called from the new thread. The return value
917
 * of @func becomes the return value of the thread, which can be obtained
918
 * with g_thread_join().
919
 *
920
 * The @name can be useful for discriminating threads in a debugger.
921
 * It is not used for other purposes and does not have to be unique.
922
 * Some systems restrict the length of @name to 16 bytes.
923
 *
924
 * If the thread can not be created the program aborts. See
925
 * g_thread_try_new() if you want to attempt to deal with failures.
926
 *
927
 * If you are using threads to offload (potentially many) short-lived tasks,
928
 * #GThreadPool may be more appropriate than manually spawning and tracking
929
 * multiple #GThreads.
930
 *
931
 * To free the struct returned by this function, use g_thread_unref().
932
 * Note that g_thread_join() implicitly unrefs the #GThread as well.
933
 *
934
 * New threads by default inherit their scheduler policy (POSIX) or thread
935
 * priority (Windows) of the thread creating the new thread.
936
 *
937
 * This behaviour changed in GLib 2.64: before threads on Windows were not
938
 * inheriting the thread priority but were spawned with the default priority.
939
 * Starting with GLib 2.64 the behaviour is now consistent between Windows and
940
 * POSIX and all threads inherit their parent thread's priority.
941
 *
942
 * Returns: (transfer full): the new #GThread
943
 *
944
 * Since: 2.32
945
 */
946
GThread *
947
g_thread_new (const gchar *name,
948
              GThreadFunc  func,
949
              gpointer     data)
950
0
{
951
0
  GError *error = NULL;
952
0
  GThread *thread;
953
954
0
  thread = g_thread_new_internal (name, g_thread_proxy, func, data, 0, &error);
955
956
0
  if G_UNLIKELY (thread == NULL)
957
0
    g_error ("creating thread '%s': %s", name ? name : "", error->message);
958
959
0
  return thread;
960
0
}
961
962
/**
963
 * g_thread_try_new:
964
 * @name: (nullable): an (optional) name for the new thread
965
 * @func: (closure data) (scope async): a function to execute in the new thread
966
 * @data: (nullable): an argument to supply to the new thread
967
 * @error: return location for error, or %NULL
968
 *
969
 * This function is the same as g_thread_new() except that
970
 * it allows for the possibility of failure.
971
 *
972
 * If a thread can not be created (due to resource limits),
973
 * @error is set and %NULL is returned.
974
 *
975
 * Returns: (transfer full): the new #GThread, or %NULL if an error occurred
976
 *
977
 * Since: 2.32
978
 */
979
GThread *
980
g_thread_try_new (const gchar  *name,
981
                  GThreadFunc   func,
982
                  gpointer      data,
983
                  GError      **error)
984
0
{
985
0
  return g_thread_new_internal (name, g_thread_proxy, func, data, 0, error);
986
0
}
987
988
GThread *
989
g_thread_new_internal (const gchar *name,
990
                       GThreadFunc proxy,
991
                       GThreadFunc func,
992
                       gpointer data,
993
                       gsize stack_size,
994
                       GError **error)
995
0
{
996
0
  g_return_val_if_fail (func != NULL, NULL);
997
998
0
  g_atomic_int_inc (&g_thread_n_created_counter);
999
1000
0
  g_trace_mark (G_TRACE_CURRENT_TIME, 0, "GLib", "GThread created", "%s", name ? name : "(unnamed)");
1001
0
  return (GThread *) g_system_thread_new (proxy, stack_size, name, func, data, error);
1002
0
}
1003
1004
/**
1005
 * g_thread_exit:
1006
 * @retval: the return value of this thread
1007
 *
1008
 * Terminates the current thread.
1009
 *
1010
 * If another thread is waiting for us using g_thread_join() then the
1011
 * waiting thread will be woken up and get @retval as the return value
1012
 * of g_thread_join().
1013
 *
1014
 * Calling g_thread_exit() with a parameter @retval is equivalent to
1015
 * returning @retval from the function @func, as given to g_thread_new().
1016
 *
1017
 * You must only call g_thread_exit() from a thread that you created
1018
 * yourself with g_thread_new() or related APIs. You must not call
1019
 * this function from a thread created with another threading library
1020
 * or or from within a #GThreadPool.
1021
 */
1022
void
1023
g_thread_exit (gpointer retval)
1024
0
{
1025
0
  GRealThread* real = (GRealThread*) g_thread_self ();
1026
1027
0
  if G_UNLIKELY (!real->ours)
1028
0
    g_error ("attempt to g_thread_exit() a thread not created by GLib");
1029
1030
0
  real->retval = retval;
1031
1032
0
  g_system_thread_exit ();
1033
0
}
1034
1035
/**
1036
 * g_thread_join:
1037
 * @thread: (transfer full): a #GThread
1038
 *
1039
 * Waits until @thread finishes, i.e. the function @func, as
1040
 * given to g_thread_new(), returns or g_thread_exit() is called.
1041
 * If @thread has already terminated, then g_thread_join()
1042
 * returns immediately.
1043
 *
1044
 * Any thread can wait for any other thread by calling g_thread_join(),
1045
 * not just its 'creator'. Calling g_thread_join() from multiple threads
1046
 * for the same @thread leads to undefined behaviour.
1047
 *
1048
 * The value returned by @func or given to g_thread_exit() is
1049
 * returned by this function.
1050
 *
1051
 * g_thread_join() consumes the reference to the passed-in @thread.
1052
 * This will usually cause the #GThread struct and associated resources
1053
 * to be freed. Use g_thread_ref() to obtain an extra reference if you
1054
 * want to keep the GThread alive beyond the g_thread_join() call.
1055
 *
1056
 * Returns: (transfer full): the return value of the thread
1057
 */
1058
gpointer
1059
g_thread_join (GThread *thread)
1060
0
{
1061
0
  GRealThread *real = (GRealThread*) thread;
1062
0
  gpointer retval;
1063
1064
0
  g_return_val_if_fail (thread, NULL);
1065
0
  g_return_val_if_fail (real->ours, NULL);
1066
1067
0
  g_system_thread_wait (real);
1068
1069
0
  retval = real->retval;
1070
1071
  /* Just to make sure, this isn't used any more */
1072
0
  thread->joinable = 0;
1073
1074
0
  g_thread_unref (thread);
1075
1076
0
  return retval;
1077
0
}
1078
1079
/**
1080
 * g_thread_self:
1081
 *
1082
 * This function returns the #GThread corresponding to the
1083
 * current thread. Note that this function does not increase
1084
 * the reference count of the returned struct.
1085
 *
1086
 * This function will return a #GThread even for threads that
1087
 * were not created by GLib (i.e. those created by other threading
1088
 * APIs). This may be useful for thread identification purposes
1089
 * (i.e. comparisons) but you must not use GLib functions (such
1090
 * as g_thread_join()) on these threads.
1091
 *
1092
 * Returns: (transfer none): the #GThread representing the current thread
1093
 */
1094
GThread*
1095
g_thread_self (void)
1096
0
{
1097
0
  GRealThread* thread = g_private_get (&g_thread_specific_private);
1098
1099
0
  if (!thread)
1100
0
    {
1101
      /* If no thread data is available, provide and set one.
1102
       * This can happen for the main thread and for threads
1103
       * that are not created by GLib.
1104
       */
1105
0
      thread = g_slice_new0 (GRealThread);
1106
0
      thread->ref_count = 1;
1107
1108
0
      g_private_set (&g_thread_specific_private, thread);
1109
0
    }
1110
1111
0
  return (GThread*) thread;
1112
0
}
1113
1114
/**
1115
 * g_thread_get_name:
1116
 * @thread: a thread
1117
 *
1118
 * Gets the name of the thread.
1119
 *
1120
 * This function is intended for debugging purposes.
1121
 *
1122
 * Returns: the name of the thread
1123
 *
1124
 * Since: 2.84
1125
 */
1126
const char *
1127
g_thread_get_name (GThread *thread)
1128
0
{
1129
0
  GRealThread *real = (GRealThread*) thread;
1130
1131
0
  return real->name;
1132
0
}
1133
1134
/**
1135
 * g_get_num_processors:
1136
 *
1137
 * Determine the approximate number of threads that the system will
1138
 * schedule simultaneously for this process.  This is intended to be
1139
 * used as a parameter to g_thread_pool_new() for CPU bound tasks and
1140
 * similar cases.
1141
 *
1142
 * On platforms where enough information is known, this will be the number of 
1143
 * high performance cores and will not include low power ‘efficiency’ cores. 
1144
 * Use platform specific APIs to query for low power cores if needed.
1145
 *
1146
 * Returns: Number of schedulable threads, always greater than 0
1147
 *
1148
 * Since: 2.36
1149
 */
1150
guint
1151
g_get_num_processors (void)
1152
0
{
1153
#ifdef G_OS_WIN32
1154
  unsigned int count;
1155
  SYSTEM_INFO sysinfo;
1156
  DWORD_PTR process_cpus;
1157
  DWORD_PTR system_cpus;
1158
1159
  /* This *never* fails, use it as fallback */
1160
  GetNativeSystemInfo (&sysinfo);
1161
  count = (int) sysinfo.dwNumberOfProcessors;
1162
1163
  if (GetProcessAffinityMask (GetCurrentProcess (),
1164
                              &process_cpus, &system_cpus))
1165
    {
1166
      unsigned int af_count;
1167
1168
      for (af_count = 0; process_cpus != 0; process_cpus >>= 1)
1169
        if (process_cpus & 1)
1170
          af_count++;
1171
1172
      /* Prefer affinity-based result, if available */
1173
      if (af_count > 0)
1174
        count = af_count;
1175
    }
1176
1177
  if (count > 0)
1178
    return count;
1179
#elif defined(__APPLE__)
1180
  /* On Apple Silicon, prefer the number of performance cores to
1181
   * avoid scheduling work on slower efficiency cores.
1182
   */
1183
  {
1184
    int32_t pcore_count = 0;
1185
    size_t len = sizeof (pcore_count);
1186
    if (sysctlbyname ("hw.perflevel0.logicalcpu", &pcore_count, &len, NULL, 0) == 0 &&
1187
        pcore_count > 0)
1188
      return pcore_count;
1189
  }
1190
#elif defined(_SC_NPROCESSORS_ONLN) && defined(THREADS_POSIX) && defined(HAVE_PTHREAD_GETAFFINITY_NP)
1191
  {
1192
0
    int ncores = MIN (sysconf (_SC_NPROCESSORS_ONLN), CPU_SETSIZE);
1193
0
    cpu_set_t cpu_mask;
1194
0
    CPU_ZERO (&cpu_mask);
1195
1196
0
    int af_count = 0;
1197
0
    int err = pthread_getaffinity_np (pthread_self (), sizeof (cpu_mask), &cpu_mask);
1198
0
    if (!err)
1199
0
      af_count = CPU_COUNT (&cpu_mask);
1200
1201
0
    int count = (af_count > 0) ? af_count : ncores;
1202
0
    return count;
1203
0
  }
1204
#elif defined(_SC_NPROCESSORS_ONLN)
1205
  {
1206
    int count;
1207
1208
    count = sysconf (_SC_NPROCESSORS_ONLN);
1209
    if (count > 0)
1210
      return count;
1211
  }
1212
#elif defined HW_NCPU
1213
  {
1214
    int mib[2], count = 0;
1215
    size_t len;
1216
1217
    mib[0] = CTL_HW;
1218
    mib[1] = HW_NCPU;
1219
    len = sizeof(count);
1220
1221
    if (sysctl (mib, 2, &count, &len, NULL, 0) == 0 && count > 0)
1222
      return count;
1223
  }
1224
#endif
1225
1226
0
  return 1; /* Fallback */
1227
0
}
1228
1229
/**
1230
 * g_mutex_init:
1231
 * @mutex: an uninitialized #GMutex
1232
 *
1233
 * Initializes a #GMutex so that it can be used.
1234
 *
1235
 * This function is useful to initialize a mutex that has been
1236
 * allocated on the stack, or as part of a larger structure.
1237
 * It is not necessary to initialize a mutex that has been
1238
 * statically allocated.
1239
 *
1240
 * |[<!-- language="C" -->
1241
 *   typedef struct {
1242
 *     GMutex m;
1243
 *     ...
1244
 *   } Blob;
1245
 *
1246
 * Blob *b;
1247
 *
1248
 * b = g_new (Blob, 1);
1249
 * g_mutex_init (&b->m);
1250
 * ]|
1251
 *
1252
 * To undo the effect of g_mutex_init() when a mutex is no longer
1253
 * needed, use g_mutex_clear().
1254
 *
1255
 * Calling g_mutex_init() on an already initialized #GMutex leads
1256
 * to undefined behaviour.
1257
 *
1258
 * Since: 2.32
1259
 */
1260
void
1261
g_mutex_init (GMutex *mutex)
1262
0
{
1263
0
  g_mutex_init_impl (mutex);
1264
0
}
1265
1266
/**
1267
 * g_mutex_clear:
1268
 * @mutex: an initialized #GMutex
1269
 *
1270
 * Frees the resources allocated to a mutex with g_mutex_init().
1271
 *
1272
 * This function should not be used with a #GMutex that has been
1273
 * statically allocated.
1274
 *
1275
 * Calling g_mutex_clear() on a locked mutex leads to undefined
1276
 * behaviour.
1277
 *
1278
 * Since: 2.32
1279
 */
1280
void
1281
g_mutex_clear (GMutex *mutex)
1282
0
{
1283
0
  g_mutex_clear_impl (mutex);
1284
0
}
1285
1286
/**
1287
 * g_mutex_lock:
1288
 * @mutex: a #GMutex
1289
 *
1290
 * Locks @mutex. If @mutex is already locked by another thread, the
1291
 * current thread will block until @mutex is unlocked by the other
1292
 * thread.
1293
 *
1294
 * #GMutex is neither guaranteed to be recursive nor to be
1295
 * non-recursive.  As such, calling g_mutex_lock() on a #GMutex that has
1296
 * already been locked by the same thread results in undefined behaviour
1297
 * (including but not limited to deadlocks).
1298
 */
1299
void
1300
g_mutex_lock (GMutex *mutex)
1301
412k
{
1302
412k
  g_mutex_lock_impl (mutex);
1303
412k
}
1304
1305
/**
1306
 * g_mutex_unlock:
1307
 * @mutex: a #GMutex
1308
 *
1309
 * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
1310
 * call for @mutex, it will become unblocked and can lock @mutex itself.
1311
 *
1312
 * Calling g_mutex_unlock() on a mutex that is not locked by the
1313
 * current thread leads to undefined behaviour.
1314
 */
1315
void
1316
g_mutex_unlock (GMutex *mutex)
1317
412k
{
1318
412k
  g_mutex_unlock_impl (mutex);
1319
412k
}
1320
1321
/**
1322
 * g_mutex_trylock:
1323
 * @mutex: a #GMutex
1324
 *
1325
 * Tries to lock @mutex. If @mutex is already locked by another thread,
1326
 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1327
 * %TRUE.
1328
 *
1329
 * #GMutex is neither guaranteed to be recursive nor to be
1330
 * non-recursive.  As such, calling g_mutex_lock() on a #GMutex that has
1331
 * already been locked by the same thread results in undefined behaviour
1332
 * (including but not limited to deadlocks or arbitrary return values).
1333
 *
1334
 * Returns: %TRUE if @mutex could be locked
1335
 */
1336
gboolean
1337
g_mutex_trylock (GMutex *mutex)
1338
0
{
1339
0
  return g_mutex_trylock_impl (mutex);
1340
0
}
1341
1342
/**
1343
 * g_rec_mutex_init:
1344
 * @rec_mutex: an uninitialized #GRecMutex
1345
 *
1346
 * Initializes a #GRecMutex so that it can be used.
1347
 *
1348
 * This function is useful to initialize a recursive mutex
1349
 * that has been allocated on the stack, or as part of a larger
1350
 * structure.
1351
 *
1352
 * It is not necessary to initialise a recursive mutex that has been
1353
 * statically allocated.
1354
 *
1355
 * |[<!-- language="C" -->
1356
 *   typedef struct {
1357
 *     GRecMutex m;
1358
 *     ...
1359
 *   } Blob;
1360
 *
1361
 * Blob *b;
1362
 *
1363
 * b = g_new (Blob, 1);
1364
 * g_rec_mutex_init (&b->m);
1365
 * ]|
1366
 *
1367
 * Calling g_rec_mutex_init() on an already initialized #GRecMutex
1368
 * leads to undefined behaviour.
1369
 *
1370
 * To undo the effect of g_rec_mutex_init() when a recursive mutex
1371
 * is no longer needed, use g_rec_mutex_clear().
1372
 *
1373
 * Since: 2.32
1374
 */
1375
void
1376
g_rec_mutex_init (GRecMutex *rec_mutex)
1377
0
{
1378
0
  g_rec_mutex_init_impl (rec_mutex);
1379
0
}
1380
1381
/**
1382
 * g_rec_mutex_clear:
1383
 * @rec_mutex: an initialized #GRecMutex
1384
 *
1385
 * Frees the resources allocated to a recursive mutex with
1386
 * g_rec_mutex_init().
1387
 *
1388
 * This function should not be used with a #GRecMutex that has been
1389
 * statically allocated.
1390
 *
1391
 * Calling g_rec_mutex_clear() on a locked recursive mutex leads
1392
 * to undefined behaviour.
1393
 *
1394
 * Since: 2.32
1395
 */
1396
void
1397
g_rec_mutex_clear (GRecMutex *rec_mutex)
1398
0
{
1399
0
  g_rec_mutex_clear_impl (rec_mutex);
1400
0
}
1401
1402
/**
1403
 * g_rec_mutex_lock:
1404
 * @rec_mutex: a #GRecMutex
1405
 *
1406
 * Locks @rec_mutex. If @rec_mutex is already locked by another
1407
 * thread, the current thread will block until @rec_mutex is
1408
 * unlocked by the other thread. If @rec_mutex is already locked
1409
 * by the current thread, the 'lock count' of @rec_mutex is increased.
1410
 * The mutex will only become available again when it is unlocked
1411
 * as many times as it has been locked.
1412
 *
1413
 * Since: 2.32
1414
 */
1415
void
1416
g_rec_mutex_lock (GRecMutex *mutex)
1417
84
{
1418
84
  g_rec_mutex_lock_impl (mutex);
1419
84
}
1420
1421
/**
1422
 * g_rec_mutex_unlock:
1423
 * @rec_mutex: a #GRecMutex
1424
 *
1425
 * Unlocks @rec_mutex. If another thread is blocked in a
1426
 * g_rec_mutex_lock() call for @rec_mutex, it will become unblocked
1427
 * and can lock @rec_mutex itself.
1428
 *
1429
 * Calling g_rec_mutex_unlock() on a recursive mutex that is not
1430
 * locked by the current thread leads to undefined behaviour.
1431
 *
1432
 * Since: 2.32
1433
 */
1434
void
1435
g_rec_mutex_unlock (GRecMutex *rec_mutex)
1436
84
{
1437
84
  g_rec_mutex_unlock_impl (rec_mutex);
1438
84
}
1439
1440
/**
1441
 * g_rec_mutex_trylock:
1442
 * @rec_mutex: a #GRecMutex
1443
 *
1444
 * Tries to lock @rec_mutex. If @rec_mutex is already locked
1445
 * by another thread, it immediately returns %FALSE. Otherwise
1446
 * it locks @rec_mutex and returns %TRUE.
1447
 *
1448
 * Returns: %TRUE if @rec_mutex could be locked
1449
 *
1450
 * Since: 2.32
1451
 */
1452
gboolean
1453
g_rec_mutex_trylock (GRecMutex *rec_mutex)
1454
0
{
1455
0
  return g_rec_mutex_trylock_impl (rec_mutex);
1456
0
}
1457
1458
/* {{{1 GRWLock */
1459
1460
/**
1461
 * g_rw_lock_init:
1462
 * @rw_lock: an uninitialized #GRWLock
1463
 *
1464
 * Initializes a #GRWLock so that it can be used.
1465
 *
1466
 * This function is useful to initialize a lock that has been
1467
 * allocated on the stack, or as part of a larger structure.  It is not
1468
 * necessary to initialise a reader-writer lock that has been statically
1469
 * allocated.
1470
 *
1471
 * |[<!-- language="C" -->
1472
 *   typedef struct {
1473
 *     GRWLock l;
1474
 *     ...
1475
 *   } Blob;
1476
 *
1477
 * Blob *b;
1478
 *
1479
 * b = g_new (Blob, 1);
1480
 * g_rw_lock_init (&b->l);
1481
 * ]|
1482
 *
1483
 * To undo the effect of g_rw_lock_init() when a lock is no longer
1484
 * needed, use g_rw_lock_clear().
1485
 *
1486
 * Calling g_rw_lock_init() on an already initialized #GRWLock leads
1487
 * to undefined behaviour.
1488
 *
1489
 * Since: 2.32
1490
 */
1491
void
1492
g_rw_lock_init (GRWLock *rw_lock)
1493
0
{
1494
0
  g_rw_lock_init_impl (rw_lock);
1495
0
}
1496
1497
/**
1498
 * g_rw_lock_clear:
1499
 * @rw_lock: an initialized #GRWLock
1500
 *
1501
 * Frees the resources allocated to a lock with g_rw_lock_init().
1502
 *
1503
 * This function should not be used with a #GRWLock that has been
1504
 * statically allocated.
1505
 *
1506
 * Calling g_rw_lock_clear() when any thread holds the lock
1507
 * leads to undefined behaviour.
1508
 *
1509
 * Since: 2.32
1510
 */
1511
void
1512
g_rw_lock_clear (GRWLock *rw_lock)
1513
0
{
1514
0
  g_rw_lock_clear_impl (rw_lock);
1515
0
}
1516
1517
/**
1518
 * g_rw_lock_writer_lock:
1519
 * @rw_lock: a #GRWLock
1520
 *
1521
 * Obtain a write lock on @rw_lock. If another thread currently holds
1522
 * a read or write lock on @rw_lock, the current thread will block
1523
 * until all other threads have dropped their locks on @rw_lock.
1524
 *
1525
 * Calling g_rw_lock_writer_lock() while the current thread already
1526
 * owns a read or write lock on @rw_lock leads to undefined behaviour.
1527
 *
1528
 * Since: 2.32
1529
 */
1530
void
1531
g_rw_lock_writer_lock (GRWLock *rw_lock)
1532
440
{
1533
440
  g_rw_lock_writer_lock_impl (rw_lock);
1534
440
}
1535
1536
/**
1537
 * g_rw_lock_writer_trylock:
1538
 * @rw_lock: a #GRWLock
1539
 *
1540
 * Tries to obtain a write lock on @rw_lock. If another thread
1541
 * currently holds a read or write lock on @rw_lock, it immediately
1542
 * returns %FALSE.
1543
 * Otherwise it locks @rw_lock and returns %TRUE.
1544
 *
1545
 * Returns: %TRUE if @rw_lock could be locked
1546
 *
1547
 * Since: 2.32
1548
 */
1549
gboolean
1550
g_rw_lock_writer_trylock (GRWLock *rw_lock)
1551
0
{
1552
0
  return g_rw_lock_writer_trylock_impl (rw_lock);
1553
0
}
1554
1555
/**
1556
 * g_rw_lock_writer_unlock:
1557
 * @rw_lock: a #GRWLock
1558
 *
1559
 * Release a write lock on @rw_lock.
1560
 *
1561
 * Calling g_rw_lock_writer_unlock() on a lock that is not held
1562
 * by the current thread leads to undefined behaviour.
1563
 *
1564
 * Since: 2.32
1565
 */
1566
void
1567
g_rw_lock_writer_unlock (GRWLock *rw_lock)
1568
440
{
1569
440
  g_rw_lock_writer_unlock_impl (rw_lock);
1570
440
}
1571
1572
/**
1573
 * g_rw_lock_reader_lock:
1574
 * @rw_lock: a #GRWLock
1575
 *
1576
 * Obtain a read lock on @rw_lock. If another thread currently holds
1577
 * the write lock on @rw_lock, the current thread will block until the
1578
 * write lock was (held and) released. If another thread does not hold
1579
 * the write lock, but is waiting for it, it is implementation defined
1580
 * whether the reader or writer will block. Read locks can be taken
1581
 * recursively.
1582
 *
1583
 * Calling g_rw_lock_reader_lock() while the current thread already
1584
 * owns a write lock leads to undefined behaviour. Read locks however
1585
 * can be taken recursively, in which case you need to make sure to
1586
 * call g_rw_lock_reader_unlock() the same amount of times.
1587
 *
1588
 * It is implementation-defined how many read locks are allowed to be
1589
 * held on the same lock simultaneously. If the limit is hit,
1590
 * or if a deadlock is detected, a critical warning will be emitted.
1591
 *
1592
 * Since: 2.32
1593
 */
1594
void
1595
g_rw_lock_reader_lock (GRWLock *rw_lock)
1596
280
{
1597
280
  g_rw_lock_reader_lock_impl (rw_lock);
1598
280
}
1599
1600
/**
1601
 * g_rw_lock_reader_trylock:
1602
 * @rw_lock: a #GRWLock
1603
 *
1604
 * Tries to obtain a read lock on @rw_lock and returns %TRUE if
1605
 * the read lock was successfully obtained. Otherwise it
1606
 * returns %FALSE.
1607
 *
1608
 * Returns: %TRUE if @rw_lock could be locked
1609
 *
1610
 * Since: 2.32
1611
 */
1612
gboolean
1613
g_rw_lock_reader_trylock (GRWLock *rw_lock)
1614
0
{
1615
0
  return g_rw_lock_reader_trylock_impl (rw_lock);
1616
0
}
1617
1618
/**
1619
 * g_rw_lock_reader_unlock:
1620
 * @rw_lock: a #GRWLock
1621
 *
1622
 * Release a read lock on @rw_lock.
1623
 *
1624
 * Calling g_rw_lock_reader_unlock() on a lock that is not held
1625
 * by the current thread leads to undefined behaviour.
1626
 *
1627
 * Since: 2.32
1628
 */
1629
void
1630
g_rw_lock_reader_unlock (GRWLock *rw_lock)
1631
280
{
1632
280
  g_rw_lock_reader_unlock_impl (rw_lock);
1633
280
}
1634
1635
/* {{{1 GCond */
1636
1637
/**
1638
 * g_cond_init:
1639
 * @cond: an uninitialized #GCond
1640
 *
1641
 * Initialises a #GCond so that it can be used.
1642
 *
1643
 * This function is useful to initialise a #GCond that has been
1644
 * allocated as part of a larger structure.  It is not necessary to
1645
 * initialise a #GCond that has been statically allocated.
1646
 *
1647
 * To undo the effect of g_cond_init() when a #GCond is no longer
1648
 * needed, use g_cond_clear().
1649
 *
1650
 * Calling g_cond_init() on an already-initialised #GCond leads
1651
 * to undefined behaviour.
1652
 *
1653
 * Since: 2.32
1654
 */
1655
void
1656
g_cond_init (GCond *cond)
1657
0
{
1658
0
  g_cond_init_impl (cond);
1659
0
}
1660
1661
/**
1662
 * g_cond_clear:
1663
 * @cond: an initialised #GCond
1664
 *
1665
 * Frees the resources allocated to a #GCond with g_cond_init().
1666
 *
1667
 * This function should not be used with a #GCond that has been
1668
 * statically allocated.
1669
 *
1670
 * Calling g_cond_clear() for a #GCond on which threads are
1671
 * blocking leads to undefined behaviour.
1672
 *
1673
 * Since: 2.32
1674
 */
1675
void
1676
g_cond_clear (GCond *cond)
1677
0
{
1678
0
  g_cond_clear_impl (cond);
1679
0
}
1680
1681
/**
1682
 * g_cond_wait:
1683
 * @cond: a #GCond
1684
 * @mutex: a #GMutex that is currently locked
1685
 *
1686
 * Atomically releases @mutex and waits until @cond is signalled.
1687
 * When this function returns, @mutex is locked again and owned by the
1688
 * calling thread.
1689
 *
1690
 * When using condition variables, it is possible that a spurious wakeup
1691
 * may occur (ie: g_cond_wait() returns even though g_cond_signal() was
1692
 * not called).  It's also possible that a stolen wakeup may occur.
1693
 * This is when g_cond_signal() is called, but another thread acquires
1694
 * @mutex before this thread and modifies the state of the program in
1695
 * such a way that when g_cond_wait() is able to return, the expected
1696
 * condition is no longer met.
1697
 *
1698
 * For this reason, g_cond_wait() must always be used in a loop.  See
1699
 * the documentation for #GCond for a complete example.
1700
 **/
1701
void
1702
g_cond_wait (GCond  *cond,
1703
             GMutex *mutex)
1704
0
{
1705
0
  g_cond_wait_impl (cond, mutex);
1706
0
}
1707
1708
/**
1709
 * g_cond_signal:
1710
 * @cond: a #GCond
1711
 *
1712
 * If threads are waiting for @cond, at least one of them is unblocked.
1713
 * If no threads are waiting for @cond, this function has no effect.
1714
 * It is good practice to hold the same lock as the waiting thread
1715
 * while calling this function, though not required.
1716
 */
1717
void
1718
g_cond_signal (GCond *cond)
1719
0
{
1720
0
  g_cond_signal_impl (cond);
1721
0
}
1722
1723
/**
1724
 * g_cond_broadcast:
1725
 * @cond: a #GCond
1726
 *
1727
 * If threads are waiting for @cond, all of them are unblocked.
1728
 * If no threads are waiting for @cond, this function has no effect.
1729
 * It is good practice to lock the same mutex as the waiting threads
1730
 * while calling this function, though not required.
1731
 */
1732
void
1733
g_cond_broadcast (GCond *cond)
1734
14
{
1735
14
  g_cond_broadcast_impl (cond);
1736
14
}
1737
1738
/**
1739
 * g_cond_wait_until:
1740
 * @cond: a #GCond
1741
 * @mutex: a #GMutex that is currently locked
1742
 * @end_time: the monotonic time to wait until
1743
 *
1744
 * Waits until either @cond is signalled or @end_time has passed.
1745
 *
1746
 * As with g_cond_wait() it is possible that a spurious or stolen wakeup
1747
 * could occur.  For that reason, waiting on a condition variable should
1748
 * always be in a loop, based on an explicitly-checked predicate.
1749
 *
1750
 * %TRUE is returned if the condition variable was signalled (or in the
1751
 * case of a spurious wakeup).  %FALSE is returned if @end_time has
1752
 * passed.
1753
 *
1754
 * The following code shows how to correctly perform a timed wait on a
1755
 * condition variable (extending the example presented in the
1756
 * documentation for #GCond):
1757
 *
1758
 * |[<!-- language="C" -->
1759
 * gpointer
1760
 * pop_data_timed (void)
1761
 * {
1762
 *   gint64 end_time;
1763
 *   gpointer data;
1764
 *
1765
 *   g_mutex_lock (&data_mutex);
1766
 *
1767
 *   end_time = g_get_monotonic_time () + 5 * G_TIME_SPAN_SECOND;
1768
 *   while (!current_data)
1769
 *     if (!g_cond_wait_until (&data_cond, &data_mutex, end_time))
1770
 *       {
1771
 *         // timeout has passed.
1772
 *         g_mutex_unlock (&data_mutex);
1773
 *         return NULL;
1774
 *       }
1775
 *
1776
 *   // there is data for us
1777
 *   data = current_data;
1778
 *   current_data = NULL;
1779
 *
1780
 *   g_mutex_unlock (&data_mutex);
1781
 *
1782
 *   return data;
1783
 * }
1784
 * ]|
1785
 *
1786
 * Notice that the end time is calculated once, before entering the
1787
 * loop and reused.  This is the motivation behind the use of absolute
1788
 * time on this API -- if a relative time of 5 seconds were passed
1789
 * directly to the call and a spurious wakeup occurred, the program would
1790
 * have to start over waiting again (which would lead to a total wait
1791
 * time of more than 5 seconds).
1792
 *
1793
 * Returns: %TRUE on a signal, %FALSE on a timeout
1794
 * Since: 2.32
1795
 **/
1796
gboolean
1797
g_cond_wait_until (GCond  *cond,
1798
                   GMutex *mutex,
1799
                   gint64  end_time)
1800
0
{
1801
0
  return g_cond_wait_until_impl (cond, mutex, end_time);
1802
0
}
1803
1804
/* {{{1 GPrivate */
1805
1806
/**
1807
 * GPrivate:
1808
 *
1809
 * The #GPrivate struct is an opaque data structure to represent a
1810
 * thread-local data key. It is approximately equivalent to the
1811
 * pthread_setspecific()/pthread_getspecific() APIs on POSIX and to
1812
 * TlsSetValue()/TlsGetValue() on Windows.
1813
 *
1814
 * If you don't already know why you might want this functionality,
1815
 * then you probably don't need it.
1816
 *
1817
 * #GPrivate is a very limited resource (as far as 128 per program,
1818
 * shared between all libraries). It is also not possible to destroy a
1819
 * #GPrivate after it has been used. As such, it is only ever acceptable
1820
 * to use #GPrivate in static scope, and even then sparingly so.
1821
 *
1822
 * See G_PRIVATE_INIT() for a couple of examples.
1823
 *
1824
 * The #GPrivate structure should be considered opaque.  It should only
1825
 * be accessed via the g_private_ functions.
1826
 */
1827
1828
/**
1829
 * G_PRIVATE_INIT:
1830
 * @notify: a #GDestroyNotify
1831
 *
1832
 * A macro to assist with the static initialisation of a #GPrivate.
1833
 *
1834
 * This macro is useful for the case that a #GDestroyNotify function
1835
 * should be associated with the key.  This is needed when the key will be
1836
 * used to point at memory that should be deallocated when the thread
1837
 * exits.
1838
 *
1839
 * Additionally, the #GDestroyNotify will also be called on the previous
1840
 * value stored in the key when g_private_replace() is used.
1841
 *
1842
 * If no #GDestroyNotify is needed, then use of this macro is not
1843
 * required -- if the #GPrivate is declared in static scope then it will
1844
 * be properly initialised by default (ie: to all zeros).  See the
1845
 * examples below.
1846
 *
1847
 * |[<!-- language="C" -->
1848
 * static GPrivate name_key = G_PRIVATE_INIT (g_free);
1849
 *
1850
 * // return value should not be freed
1851
 * const gchar *
1852
 * get_local_name (void)
1853
 * {
1854
 *   return g_private_get (&name_key);
1855
 * }
1856
 *
1857
 * void
1858
 * set_local_name (const gchar *name)
1859
 * {
1860
 *   g_private_replace (&name_key, g_strdup (name));
1861
 * }
1862
 *
1863
 *
1864
 * static GPrivate count_key;   // no free function
1865
 *
1866
 * gint
1867
 * get_local_count (void)
1868
 * {
1869
 *   return GPOINTER_TO_INT (g_private_get (&count_key));
1870
 * }
1871
 *
1872
 * void
1873
 * set_local_count (gint count)
1874
 * {
1875
 *   g_private_set (&count_key, GINT_TO_POINTER (count));
1876
 * }
1877
 * ]|
1878
 *
1879
 * Since: 2.32
1880
 **/
1881
1882
/**
1883
 * g_private_get:
1884
 * @key: a #GPrivate
1885
 *
1886
 * Returns the current value of the thread local variable @key.
1887
 *
1888
 * If the value has not yet been set in this thread, %NULL is returned.
1889
 * Values are never copied between threads (when a new thread is
1890
 * created, for example).
1891
 *
1892
 * Returns: the thread-local value
1893
 */
1894
gpointer
1895
g_private_get (GPrivate *key)
1896
2.64k
{
1897
2.64k
  return g_private_get_impl (key);
1898
2.64k
}
1899
1900
/**
1901
 * g_private_set:
1902
 * @key: a #GPrivate
1903
 * @value: the new value
1904
 *
1905
 * Sets the thread local variable @key to have the value @value in the
1906
 * current thread.
1907
 *
1908
 * This function differs from g_private_replace() in the following way:
1909
 * the #GDestroyNotify for @key is not called on the old value.
1910
 */
1911
void
1912
g_private_set (GPrivate *key,
1913
               gpointer  value)
1914
5.28k
{
1915
5.28k
  g_private_set_impl (key, value);
1916
5.28k
}
1917
1918
/**
1919
 * g_private_replace:
1920
 * @key: a #GPrivate
1921
 * @value: the new value
1922
 *
1923
 * Sets the thread local variable @key to have the value @value in the
1924
 * current thread.
1925
 *
1926
 * This function differs from g_private_set() in the following way: if
1927
 * the previous value was non-%NULL then the #GDestroyNotify handler for
1928
 * @key is run on it.
1929
 *
1930
 * Since: 2.32
1931
 **/
1932
void
1933
g_private_replace (GPrivate *key,
1934
                   gpointer  value)
1935
0
{
1936
0
  g_private_replace_impl (key, value);
1937
0
}
1938
1939
/* {{{1 GThread */
1940
1941
/**
1942
 * g_thread_yield:
1943
 *
1944
 * Causes the calling thread to voluntarily relinquish the CPU, so
1945
 * that other threads can run.
1946
 *
1947
 * This function is often used as a method to make busy wait less evil.
1948
 */
1949
void
1950
g_thread_yield (void)
1951
0
{
1952
0
  g_thread_yield_impl ();
1953
0
}
1954
1955
/* Epilogue {{{1 */
1956
/* vim: set foldmethod=marker: */