Stxxl
1.4.0
|
00001 /*************************************************************************** 00002 * common/seed.cpp 00003 * 00004 * Part of the STXXL. See http://stxxl.sourceforge.net 00005 * 00006 * Copyright (C) 2007, 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de> 00007 * Copyright (C) 2008 Roman Dementiev <dementiev@ira.uka.de> 00008 * 00009 * Distributed under the Boost Software License, Version 1.0. 00010 * (See accompanying file LICENSE_1_0.txt or copy at 00011 * http://www.boost.org/LICENSE_1_0.txt) 00012 **************************************************************************/ 00013 00014 #include <cassert> 00015 #include <ctime> 00016 #ifdef STXXL_BOOST_CONFIG 00017 #include <boost/config.hpp> 00018 #endif 00019 #ifdef BOOST_MSVC 00020 #include <io.h> 00021 #include <windows.h> 00022 #else 00023 #include <unistd.h> 00024 #include <sys/time.h> 00025 #endif 00026 00027 #include <stxxl/bits/common/seed.h> 00028 #include <stxxl/bits/common/mutex.h> 00029 00030 00031 __STXXL_BEGIN_NAMESPACE 00032 00033 inline unsigned initial_seed(); 00034 00035 struct seed_generator_t { 00036 unsigned seed; 00037 mutex mtx; 00038 00039 seed_generator_t(unsigned s) : seed(s) 00040 { } 00041 }; 00042 00043 seed_generator_t & seed_generator() 00044 { 00045 static seed_generator_t sg(initial_seed()); 00046 return sg; 00047 } 00048 00049 inline unsigned initial_seed() 00050 { 00051 static bool initialized = false; 00052 assert(!initialized); // this should only be called once! 00053 00054 initialized = true; 00055 #ifdef BOOST_MSVC 00056 // GetTickCount(): ms since system start 00057 return GetTickCount() ^ GetCurrentProcessId(); 00058 #else 00059 struct timeval tv; 00060 gettimeofday(&tv, 0); 00061 00062 return tv.tv_sec ^ tv.tv_usec ^ (getpid() << 16); 00063 #endif 00064 } 00065 00066 void set_seed(unsigned seed) 00067 { 00068 scoped_mutex_lock Lock(seed_generator().mtx); 00069 seed_generator().seed = seed; 00070 } 00071 00072 unsigned get_next_seed() 00073 { 00074 scoped_mutex_lock Lock(seed_generator().mtx); 00075 return seed_generator().seed++; 00076 } 00077 00078 __STXXL_END_NAMESPACE