diff options
author | Jeroen Vermeulen <jtv@precisiontranslationtools.com> | 2015-04-22 16:43:29 +0300 |
---|---|---|
committer | Jeroen Vermeulen <jtv@precisiontranslationtools.com> | 2015-04-22 16:43:29 +0300 |
commit | 75bfb758822cc926a1852c6a86a7ce5d153a1320 (patch) | |
tree | 7a967ee360aeb4898450888b31fc2ad602d9c7e6 /util/random_test.cc | |
parent | 1083999d3e4447ac347b8bcbb04a0733ae8c3654 (diff) |
Thread-safe, platform-agnostic randomizer.
Some places in mert use srandom()/random(), but these are POSIX-specific.
The standard alternative, srand()/rand(), is not thread-safe. This module
wraps srand()/rand() in mutexes (very short-lived, so should not cost much)
so that it relies on just Boost and the C standard library, not on a Unix-like
environment.
This may reduce the width of the random numbers on some platforms: it goes
from "long int" to just "int". If that is a problem, we may have to use
Boost's randomizer utilities, or eventually, the C++ ones.
Diffstat (limited to 'util/random_test.cc')
-rw-r--r-- | util/random_test.cc | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/util/random_test.cc b/util/random_test.cc new file mode 100644 index 000000000..d1c555a0c --- /dev/null +++ b/util/random_test.cc @@ -0,0 +1,39 @@ +#include "util/random.hh" + +#define BOOST_TEST_MODULE RandomTest +#include <boost/test/unit_test.hpp> + +namespace util +{ +namespace +{ + +BOOST_AUTO_TEST_CASE(returns_different_consecutive_numbers) +{ + rand_int_init(99); + const int first = rand_int(), second = rand_int(), third = rand_int(); + // Sometimes you'll get the same number twice in a row, but generally the + // randomizer returns different numbers. + BOOST_CHECK(second != first || third != first); +} + +BOOST_AUTO_TEST_CASE(returns_different_numbers_for_different_seeds) +{ + rand_int_init(1); + const int one1 = rand_int(), one2 = rand_int(); + rand_int_init(2); + const int two1 = rand_int(), two2 = rand_int(); + BOOST_CHECK(two1 != one1 || two2 != two1); +} + +BOOST_AUTO_TEST_CASE(returns_same_sequence_for_same_seed) +{ + rand_int_init(1); + const int first = rand_int(); + rand_int_init(1); + const int second = rand_int(); + BOOST_CHECK_EQUAL(first, second); +} + +} // namespace +} // namespace util |