From b0f69d46a95f1b0984bd758ce840572a20593a77 Mon Sep 17 00:00:00 2001 From: Matthias Koefferlein Date: Mon, 9 Jul 2018 00:55:41 +0200 Subject: [PATCH] WIP: one first basic Thread test. --- src/tl/unit_tests/tlThreads.cc | 83 ++++++++++++++++++++++++++++++++ src/tl/unit_tests/unit_tests.pro | 1 + 2 files changed, 84 insertions(+) create mode 100644 src/tl/unit_tests/tlThreads.cc diff --git a/src/tl/unit_tests/tlThreads.cc b/src/tl/unit_tests/tlThreads.cc new file mode 100644 index 000000000..bef5b19d7 --- /dev/null +++ b/src/tl/unit_tests/tlThreads.cc @@ -0,0 +1,83 @@ + +/* + + KLayout Layout Viewer + Copyright (C) 2006-2018 Matthias Koefferlein + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +*/ + +#include "tlThreads.h" +#include "tlUnitTest.h" + +#include + +#if defined(WIN32) +#include +inline void usleep(long us) +{ + Sleep(us / 1000); +} +#else +#include +#endif + +class MyThread : public tl::Thread +{ +public: + MyThread () : m_value (0), m_stop (false) { } + + int value () + { + tl::MutexLocker locker (&m_lock); + return m_value; + } + + void run () + { + for (int i = 0; i < 10 && !m_stop; ++i) { + { + tl::MutexLocker locker (&m_lock); + ++m_value; + } + usleep (10000); + } + } + + void stop () + { + m_stop = true; + } + +private: + int m_value; + bool m_stop; + tl::Mutex m_lock; +}; + +// basic: concurrency, ability to stop async, wait +TEST(1) +{ + MyThread my_thread; + my_thread.start (); + while (my_thread.value () < 5) + ; + my_thread.stop (); + my_thread.wait (); + // stopped before 10 and after 5 + EXPECT_EQ (my_thread.value () >= 5 && my_thread.value () < 10, true); +} + diff --git a/src/tl/unit_tests/unit_tests.pro b/src/tl/unit_tests/unit_tests.pro index 699e1d422..59ba2fddd 100644 --- a/src/tl/unit_tests/unit_tests.pro +++ b/src/tl/unit_tests/unit_tests.pro @@ -25,6 +25,7 @@ SOURCES = \ tlStableVector.cc \ tlString.cc \ tlThreadedWorkers.cc \ + tlThreads.cc \ tlUtils.cc \ tlVariant.cc \ tlInt128Support.cc \