[glib/wip/gcleanup: 4/10] grand: restructure a bit



commit b0af5171ce5d45dd9282882c9f0a794fcceb57d3
Author: Ryan Lortie <desrt desrt ca>
Date:   Sun Mar 24 21:25:26 2013 -0400

    grand: restructure a bit
    
    Instead of having lots of 'if NULL then allocate' code segments for the
    global GRand instance, move it to a single getter function that everyone
    calls.

 glib/grand.c |   38 +++++++++++++++++---------------------
 1 files changed, 17 insertions(+), 21 deletions(-)
---
diff --git a/glib/grand.c b/glib/grand.c
index 56e443d..3f043ad 100644
--- a/glib/grand.c
+++ b/glib/grand.c
@@ -123,7 +123,6 @@
  **/
 
 G_LOCK_DEFINE_STATIC (global_random);
-static GRand* global_random = NULL;
 
 /* Period parameters */  
 #define N 624
@@ -597,6 +596,18 @@ g_rand_double_range (GRand* rand, gdouble begin, gdouble end)
   return r * end - (r - 1) * begin;
 }
 
+static GRand *
+get_global_random (void)
+{
+  static GRand *global_random;
+
+  /* called while locked */
+  if (!global_random)
+    global_random = g_rand_new ();
+
+  return global_random;
+}
+
 /**
  * g_random_boolean:
  *
@@ -617,10 +628,7 @@ g_random_int (void)
 {
   guint32 result;
   G_LOCK (global_random);
-  if (!global_random)
-    global_random = g_rand_new ();
-  
-  result = g_rand_int (global_random);
+  result = g_rand_int (get_global_random ());
   G_UNLOCK (global_random);
   return result;
 }
@@ -640,10 +648,7 @@ g_random_int_range (gint32 begin, gint32 end)
 {
   gint32 result;
   G_LOCK (global_random);
-  if (!global_random)
-    global_random = g_rand_new ();
-  
-  result = g_rand_int_range (global_random, begin, end);
+  result = g_rand_int_range (get_global_random (), begin, end);
   G_UNLOCK (global_random);
   return result;
 }
@@ -660,10 +665,7 @@ g_random_double (void)
 {
   double result;
   G_LOCK (global_random);
-  if (!global_random)
-    global_random = g_rand_new ();
-  
-  result = g_rand_double (global_random);
+  result = g_rand_double (get_global_random ());
   G_UNLOCK (global_random);
   return result;
 }
@@ -682,10 +684,7 @@ g_random_double_range (gdouble begin, gdouble end)
 {
   double result;
   G_LOCK (global_random);
-  if (!global_random)
-    global_random = g_rand_new ();
- 
-  result = g_rand_double_range (global_random, begin, end);
+  result = g_rand_double_range (get_global_random (), begin, end);
   G_UNLOCK (global_random);
   return result;
 }
@@ -701,9 +700,6 @@ void
 g_random_set_seed (guint32 seed)
 {
   G_LOCK (global_random);
-  if (!global_random)
-    global_random = g_rand_new_with_seed (seed);
-  else
-    g_rand_set_seed (global_random, seed);
+  g_rand_set_seed (get_global_random (), seed);
   G_UNLOCK (global_random);
 }


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]