summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorXavier Claessens <xavier.claessens@collabora.com>2015-02-05 10:35:42 -0500
committerXavier Claessens <xavier.claessens@collabora.com>2015-02-05 14:15:45 -0500
commita2e117de51ed911ad75a0a7982a5216953c8269e (patch)
treee966c345a9ec604cb64b101cb04f93bb358f5972
parent74c22150cf4c2f8a9c7d7fae058a7fd589a94a27 (diff)
downloadglib-wip/xclaesse/locker.tar.gz
Add GMutexLockerwip/xclaesse/locker
https://bugzilla.gnome.org/show_bug.cgi?id=744012
-rw-r--r--docs/reference/glib/glib-sections.txt5
-rw-r--r--glib/gthread.h69
2 files changed, 74 insertions, 0 deletions
diff --git a/docs/reference/glib/glib-sections.txt b/docs/reference/glib/glib-sections.txt
index f48c2f00b..45827d6da 100644
--- a/docs/reference/glib/glib-sections.txt
+++ b/docs/reference/glib/glib-sections.txt
@@ -649,6 +649,11 @@ g_mutex_trylock
g_mutex_unlock
<SUBSECTION>
+GMutexLocker
+g_mutex_locker_new
+g_mutex_locker_free
+
+<SUBSECTION>
G_LOCK_DEFINE
G_LOCK_DEFINE_STATIC
G_LOCK_EXTERN
diff --git a/glib/gthread.h b/glib/gthread.h
index 3f026f631..fe4df2400 100644
--- a/glib/gthread.h
+++ b/glib/gthread.h
@@ -266,6 +266,75 @@ void g_once_init_leave (volatile void *location,
GLIB_AVAILABLE_IN_2_36
guint g_get_num_processors (void);
+/**
+ * GMutexLocker:
+ *
+ * Opaque type. See g_mutex_locker_new() for details.
+ * Since: 2.44
+ */
+typedef void GMutexLocker;
+
+/**
+ * g_mutex_locker_new:
+ * @mutex: a mutex to lock
+ *
+ * Lock @mutex and return a new #GMutexLocker. Unlock with
+ * g_mutex_locker_free(). Using g_mutex_unlock() on @mutex
+ * while a #GMutexLocker exists can lead to undefined behaviour.
+ *
+ * This is intended to be used with g_autoptr() like this:
+ * |[
+ * typedef struct
+ * {
+ * ...
+ * GMutex mutex;
+ * ...
+ * } MyObject;
+ *
+ * static void
+ * my_object_do_stuff (MyObject *self)
+ * {
+ * g_autoptr(GMutexLocker) locker = g_mutex_locker_new (&self->mutex);
+ *
+ * // Code with mutex locked here
+ *
+ * if (cond)
+ * // No need to unlock
+ * return;
+ *
+ * // Optionally early unlock
+ * g_clear_pointer (&locker, g_mutex_locker_free);
+ *
+ * // Code with mutex unlocked here
+ * }
+ * ]|
+ *
+ * Returns: a #GMutexLocker
+ * Since: 2.44
+ */
+static inline GMutexLocker *
+g_mutex_locker_new (GMutex *mutex)
+{
+ g_mutex_lock (mutex);
+ return (GMutexLocker *) mutex;
+}
+
+/**
+ * g_mutex_locker_free:
+ * @locker: a GMutexLocker
+ *
+ * Unlock @locker's mutex. See g_mutex_locker_new() for details.
+ *
+ * Since: 2.44
+ */
+static inline void
+g_mutex_locker_free (GMutexLocker *locker)
+{
+ g_mutex_unlock ((GMutex *) locker);
+}
+
+G_DEFINE_AUTOPTR_CLEANUP_FUNC(GMutexLocker, g_mutex_locker_free)
+
G_END_DECLS
#endif /* __G_THREAD_H__ */