Dvorkam / RPG-Engine

1 stars 0 forks source link

Concurent uniform random number generator #4

Open Dvorkam opened 1 year ago

Dvorkam commented 1 year ago

This is to support threading in the future.

Dvorkam commented 1 year ago

Something like this

#include <mutex>

template <UniformRandomNumberGenerator Generator>
class ConcurrentGeneratorGeneric : public IGenerator<typename Generator::result_type> {
    Generator generator;
    std::mutex mtx; // Mutex for synchronization

public:
    using result_type = typename Generator::result_type;

    ConcurrentGeneratorGeneric(result_type seed) {
        generator.seed(seed);
    }

    constexpr result_type min() const noexcept override {
        return std::numeric_limits<result_type>::min();
    }

    constexpr result_type max() const noexcept override {
        return std::numeric_limits<result_type>::max();
    }

    result_type operator()() override {
        std::lock_guard<std::mutex> lock(mtx); // Lock the mutex
        return getRandomNumber();
    }

    result_type getRandomNumber() override {
        std::lock_guard<std::mutex> lock(mtx); // Lock the mutex
        return generator();
    }

    void seed(result_type sseq) noexcept override {
        std::lock_guard<std::mutex> lock(mtx); // Lock the mutex
        generator.seed(sseq);
    }
};