STXXL  1.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
seed.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  * lib/common/seed.cpp
3  *
4  * Part of the STXXL. See http://stxxl.sourceforge.net
5  *
6  * Copyright (C) 2007, 2008 Andreas Beckmann <[email protected]>
7  * Copyright (C) 2008 Roman Dementiev <[email protected]>
8  *
9  * Distributed under the Boost Software License, Version 1.0.
10  * (See accompanying file LICENSE_1_0.txt or copy at
11  * http://www.boost.org/LICENSE_1_0.txt)
12  **************************************************************************/
13 
14 #include <cassert>
15 #include <stxxl/bits/config.h>
17 #include <stxxl/bits/namespace.h>
18 
19 #if STXXL_WINDOWS
20  #ifndef NOMINMAX
21  #define NOMINMAX
22  #endif
23  #include <io.h>
24  #include <windows.h>
25 #else
26  #include <unistd.h>
27  #include <sys/time.h>
28 #endif
29 
31 
32 inline unsigned initial_seed();
33 
34 struct seed_generator_t {
35  unsigned seed;
36  mutex mtx;
37 
38  seed_generator_t(unsigned s) : seed(s)
39  { }
40 };
41 
42 seed_generator_t & seed_generator()
43 {
44  static seed_generator_t sg(initial_seed());
45  return sg;
46 }
47 
48 inline unsigned initial_seed()
49 {
50 #ifndef NDEBUG
51  static bool initialized = false;
52  assert(!initialized); // this should only be called once!
53 
54  initialized = true;
55 #endif // NDEBUG
56 #if STXXL_WINDOWS
57  // GetTickCount(): ms since system start
58  return GetTickCount() ^ GetCurrentProcessId();
59 #else
60  struct timeval tv;
61  gettimeofday(&tv, 0);
62 
63  return (unsigned)(tv.tv_sec ^ tv.tv_usec ^ (getpid() << 16));
64 #endif
65 }
66 
67 void set_seed(unsigned seed)
68 {
70  seed_generator().seed = seed;
71 }
72 
73 unsigned get_next_seed()
74 {
76  return seed_generator().seed++;
77 }
78 
unsigned initial_seed()
Definition: seed.cpp:48
unsigned get_next_seed()
get a seed value for prng initialization, subsequent calls return a sequence of different values ...
Definition: seed.cpp:73
seed_generator_t & seed_generator()
Definition: seed.cpp:42
Aquire a lock that&#39;s valid until the end of scope.
Definition: mutex.h:105
#define STXXL_BEGIN_NAMESPACE
Definition: namespace.h:16
void set_seed(unsigned seed)
set the global stxxl seed value
Definition: seed.cpp:67
#define STXXL_END_NAMESPACE
Definition: namespace.h:17