File: seed.cpp

package info (click to toggle)
libstxxl 1.4.0-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 5,256 kB
  • ctags: 6,830
  • sloc: cpp: 39,594; ansic: 4,217; perl: 566; sh: 555; xml: 174; makefile: 21
file content (80 lines) | stat: -rw-r--r-- 1,787 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/***************************************************************************
 *  lib/common/seed.cpp
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2007, 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de>
 *  Copyright (C) 2008 Roman Dementiev <dementiev@ira.uka.de>
 *
 *  Distributed under the Boost Software License, Version 1.0.
 *  (See accompanying file LICENSE_1_0.txt or copy at
 *  http://www.boost.org/LICENSE_1_0.txt)
 **************************************************************************/

#include <cassert>
#include <stxxl/bits/config.h>
#include <stxxl/bits/common/mutex.h>
#include <stxxl/bits/namespace.h>

#if STXXL_WINDOWS
  #ifndef NOMINMAX
    #define NOMINMAX
  #endif
  #include <io.h>
  #include <windows.h>
#else
  #include <unistd.h>
  #include <sys/time.h>
#endif


STXXL_BEGIN_NAMESPACE

inline unsigned initial_seed();

struct seed_generator_t {
    unsigned seed;
    mutex mtx;

    seed_generator_t(unsigned s) : seed(s)
    { }
};

seed_generator_t & seed_generator()
{
    static seed_generator_t sg(initial_seed());
    return sg;
}

inline unsigned initial_seed()
{
#ifndef NDEBUG
    static bool initialized = false;
    assert(!initialized); // this should only be called once!

    initialized = true;
#endif // NDEBUG
#if STXXL_WINDOWS
    // GetTickCount():  ms since system start
    return GetTickCount() ^ GetCurrentProcessId();
#else
    struct timeval tv;
    gettimeofday(&tv, 0);

    return tv.tv_sec ^ tv.tv_usec ^ (getpid() << 16);
#endif
}

void set_seed(unsigned seed)
{
    scoped_mutex_lock Lock(seed_generator().mtx);
    seed_generator().seed = seed;
}

unsigned get_next_seed()
{
    scoped_mutex_lock Lock(seed_generator().mtx);
    return seed_generator().seed++;
}

STXXL_END_NAMESPACE