From 0e057702db06fb03d7cafddd7c410fe5a13246ea Mon Sep 17 00:00:00 2001 From: Uli Schlachter Date: Wed, 6 Aug 2014 14:46:01 +0200 Subject: [PATCH] Add a ThreadTest to the testsuite Signed-off-by: Uli Schlachter --- Makefile.in | 2 +- test/ThreadTest.cpp | 74 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 test/ThreadTest.cpp diff --git a/Makefile.in b/Makefile.in index cfa5141b..8f676eb2 100644 --- a/Makefile.in +++ b/Makefile.in @@ -47,7 +47,7 @@ LIB_SRCS := $(addprefix src/,$(LIB_SRCS)) BIN_SRCS := src/main.cpp LIB_OBJS := $(patsubst %cpp,%o,$(LIB_SRCS)) BIN_OBJS := $(patsubst %cpp,%o,$(BIN_SRCS)) -TESTS := StringTest ConfigTest UtilsTest +TESTS := StringTest ConfigTest UtilsTest ThreadTest TESTS := $(addprefix test/,$(addsuffix .o,$(TESTS))) CLEAN := znc src/*.o test/*.o core core.* .version_extra .depend modules/.depend unittest DISTCLEAN := Makefile config.log config.status znc-buildmod \ diff --git a/test/ThreadTest.cpp b/test/ThreadTest.cpp new file mode 100644 index 00000000..7b015913 --- /dev/null +++ b/test/ThreadTest.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2004-2014 ZNC, see the NOTICE file for details. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +class CWaitingJob : public CJob { +public: + CWaitingJob(bool& destroyed) + : m_bDestroyed(destroyed), m_Mutex(), m_CV(), m_bThreadReady(false), m_bThreadDone(false) { + }; + + + ~CWaitingJob() { + EXPECT_TRUE(m_bThreadReady); + EXPECT_TRUE(m_bThreadDone); + m_bDestroyed = true; + } + + void signal() { + CMutexLocker locker(m_Mutex); + // Wait for the thread to run + while (!m_bThreadReady) + m_CV.wait(m_Mutex); + + // and signal it to exit + m_bThreadDone = true; + m_CV.broadcast(); + } + + virtual void runThread() { + CMutexLocker locker(m_Mutex); + // We are running + m_bThreadReady = true; + m_CV.broadcast(); + + // wait for our exit signal + while (!m_bThreadDone) + m_CV.wait(m_Mutex); + } + + virtual void runMain() {} + +private: + bool& m_bDestroyed; + CMutex m_Mutex; + CConditionVariable m_CV; + bool m_bThreadReady; + bool m_bThreadDone; +}; + +TEST(Thread, RunJob) { + bool destroyed = false; + CWaitingJob *pJob = new CWaitingJob(destroyed); + + CThreadPool::Get().addJob(pJob); + pJob->signal(); + + while (!destroyed) + CThreadPool::Get().handlePipeReadable(); +}