libcruft-util/test/thread/spinlock.cpp

60 lines
1.6 KiB
C++
Raw Normal View History

/*
2018-08-04 15:14:06 +10:00
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2018 Danny Robson <danny@nerdcruft.net>
*/
#include "thread/flag.hpp"
#include "thread/spinlock.hpp"
#include "thread/thread.hpp"
#include "tap.hpp"
#include <mutex>
///////////////////////////////////////////////////////////////////////////////
void
fight (cruft::thread::flag &start, cruft::thread::spinlock &l, int iterations)
{
start.wait ();
for (int count = 0; count < iterations; ++count)
std::lock_guard g (l);
};
//-----------------------------------------------------------------------------
int
main ()
{
cruft::TAP::logger tap;
cruft::thread::spinlock l;
l.lock ();
tap.expect (true, "locked without contention");
l.unlock ();
tap.expect (true, "unlocked without contention");
if (cruft::thread::thread::hardware_concurrency () < 2) {
tap.skip ("n-way fight");
} else {
constexpr int iterations = 1 << 12;
cruft::thread::flag start_flag;
std::vector<cruft::thread::thread> contestants;
for (unsigned i = 0; i < cruft::thread::thread::hardware_concurrency (); ++i)
contestants.emplace_back (fight, std::ref (start_flag), std::ref (l), iterations);
start_flag.notify_all ();
for (auto &t: contestants)
t.join ();
tap.expect (true, "n-way fight, %! contestants", cruft::thread::thread::hardware_concurrency ());
}
2018-03-20 14:50:46 +11:00
return tap.status ();
}