2018-03-15 15:21:41 +11:00
|
|
|
/*
|
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/.
|
2018-03-15 15:21:41 +11:00
|
|
|
*
|
|
|
|
* Copyright 2018 Danny Robson <danny@nerdcruft.net>
|
|
|
|
*/
|
|
|
|
|
2018-03-23 14:10:20 +11:00
|
|
|
#include "thread/event.hpp"
|
2019-06-22 15:46:34 +10:00
|
|
|
#include "thread/monitor.hpp"
|
2018-03-23 14:10:20 +11:00
|
|
|
#include "thread/semaphore.hpp"
|
2019-06-22 15:46:34 +10:00
|
|
|
#include "thread/thread.hpp"
|
|
|
|
|
|
|
|
#include "tap.hpp"
|
2018-03-15 15:21:41 +11:00
|
|
|
|
|
|
|
#include <atomic>
|
|
|
|
|
|
|
|
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
// a single atomic integer wrapper that allows precise ordering of thread
|
|
|
|
// entrance and exit for exact testing of thread interleavings.
|
|
|
|
struct foo {
|
|
|
|
foo ():
|
|
|
|
enter (0),
|
|
|
|
leave (0)
|
|
|
|
{ ; }
|
|
|
|
|
|
|
|
void
|
|
|
|
inc (void) {
|
|
|
|
enter.acquire ();
|
|
|
|
++value;
|
|
|
|
leave.release ();
|
|
|
|
}
|
|
|
|
|
|
|
|
std::atomic<int> value = 0;
|
2018-08-05 14:42:02 +10:00
|
|
|
cruft::thread::semaphore enter;
|
|
|
|
cruft::thread::semaphore leave;
|
2018-03-15 15:21:41 +11:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
int
|
|
|
|
main ()
|
|
|
|
{
|
2018-08-05 14:42:02 +10:00
|
|
|
cruft::TAP::logger tap;
|
2018-03-15 15:21:41 +11:00
|
|
|
|
2018-08-05 14:42:02 +10:00
|
|
|
cruft::thread::monitor<foo> obj;
|
2018-03-15 15:21:41 +11:00
|
|
|
const auto &value = obj->value;
|
|
|
|
auto &enter = obj->enter;
|
|
|
|
auto &leave = obj->leave;
|
|
|
|
|
2019-06-22 15:46:34 +10:00
|
|
|
cruft::thread::thread t1 ([&] () { obj->inc (); });
|
|
|
|
cruft::thread::thread t2 ([&] () { obj->inc (); });
|
2018-03-15 15:21:41 +11:00
|
|
|
|
|
|
|
tap.expect_eq (value, 0, "wrapped class was left initialised");
|
|
|
|
|
|
|
|
enter.release ();
|
|
|
|
leave.acquire ();
|
|
|
|
tap.expect_eq (value, 1, "only one thread had access");
|
|
|
|
|
|
|
|
enter.release ();
|
|
|
|
leave.acquire ();
|
|
|
|
tap.expect_eq (value, 2, "second thread got access");
|
|
|
|
|
|
|
|
t1.join ();
|
|
|
|
t2.join ();
|
|
|
|
|
|
|
|
return tap.status ();
|
|
|
|
}
|