Skip to content

Commit

Permalink
More tests for random
Browse files Browse the repository at this point in the history
  • Loading branch information
kunitoki committed Dec 15, 2024
1 parent 9238ff7 commit 516b44a
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions tests/juce_core/juce_Random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,64 @@ TEST (RandomTests, RandomNumbers)
EXPECT_TRUE (r.nextInt (n) >= 0 && r.nextInt (n) < n);
}
}

TEST (RandomTests, Concurrent)
{
class FastWaitableEvent
{
public:
void notify() { notified = true; }
void wait() const { while (! notified){} }

private:
std::atomic<bool> notified = false;
};

class InvokerThread final : private Thread
{
public:
InvokerThread (std::function<void()> fn, FastWaitableEvent& notificationEvent, int numInvocationsToTrigger)
: Thread ("InvokerThread"),
invokable (fn),
notified (&notificationEvent),
numInvocations (numInvocationsToTrigger)
{
startThread();
}

~InvokerThread() { stopThread (-1); }

void waitUntilReady() const { ready.wait(); }

private:
void run() final
{
ready.notify();
notified->wait();

for (int i = numInvocations; --i >= 0;)
invokable();
}

std::function<void()> invokable;
FastWaitableEvent* notified;
FastWaitableEvent ready;
int numInvocations;
};

constexpr int numberOfInvocationsPerThread = 10000;
constexpr int numberOfThreads = 100;

std::vector<std::unique_ptr<InvokerThread>> threads;
threads.reserve ((size_t) numberOfThreads);
FastWaitableEvent start;

for (int i = numberOfThreads; --i >= 0;)
threads.push_back (std::make_unique<InvokerThread> ([] { Random::getSystemRandom().nextInt(); }, start, numberOfInvocationsPerThread));

for (auto& thread : threads)
thread->waitUntilReady();

Thread::sleep (1);
start.notify();
}

0 comments on commit 516b44a

Please sign in to comment.