From 036d26d6677e0b8e6cf284c0801b267c5f81720e Mon Sep 17 00:00:00 2001 From: Laurent Pinchart Date: Tue, 4 Oct 2022 02:42:28 +0300 Subject: test: threads: Test thread cleanup upon abnormal termination If a thread ends abnormally (that is, without retuning normally from its run() function, for instance with a direct call to pthread_cancel()), thread cleanup should still be performed. Add a test to ensure this. Signed-off-by: Laurent Pinchart Reviewed-by: Umang Jain --- test/threads.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) (limited to 'test') diff --git a/test/threads.cpp b/test/threads.cpp index d83b5833..8f366c9d 100644 --- a/test/threads.cpp +++ b/test/threads.cpp @@ -8,7 +8,9 @@ #include #include #include +#include #include +#include #include @@ -35,6 +37,35 @@ private: chrono::steady_clock::duration duration_; }; +class CancelThread : public Thread +{ +public: + CancelThread(bool &cancelled) + : cancelled_(cancelled) + { + } + +protected: + void run() + { + cancelled_ = true; + + /* + * Cancel the thread and call a guaranteed cancellation point + * (nanosleep). + */ + pthread_cancel(pthread_self()); + + struct timespec req{ 0, 100*000*000 }; + nanosleep(&req, nullptr); + + cancelled_ = false; + } + +private: + bool &cancelled_; +}; + class ThreadTest : public Test { protected: @@ -118,6 +149,22 @@ protected: return TestFail; } + /* Test thread cleanup upon abnormal termination. */ + bool cancelled = false; + bool finished = false; + + thread = std::make_unique(cancelled); + thread->finished.connect(this, [&finished]() { finished = true; }); + + thread->start(); + thread->exit(0); + thread->wait(chrono::milliseconds(1000)); + + if (!cancelled || !finished) { + cout << "Cleanup failed upon abnormal termination" << endl; + return TestFail; + } + return TestPass; } -- cgit v1.2.1