From patchwork Wed Jul 10 19:17:03 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Laurent Pinchart X-Patchwork-Id: 1644 Return-Path: Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id C7D5D6156E for ; Wed, 10 Jul 2019 21:17:41 +0200 (CEST) Received: from pendragon.ideasonboard.com (softbank126163157105.bbtec.net [126.163.157.105]) by perceval.ideasonboard.com (Postfix) with ESMTPSA id 0F58B31C for ; Wed, 10 Jul 2019 21:17:39 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1562786261; bh=K1ReDeM1dgeVepnYSOhxX5+Nhuf/mzIy79V4sFX3N4E=; h=From:To:Subject:Date:From; b=uIDpVIqwbBrW99+aow4HIUxapZZcuXB+TYxx8ccuqaYJZpEM7kY2BO7RoiCTpJJbJ jQRf8OjF4yBoPDD9NnkndMYVSf8PM9/dHObHXpEZY66QVWaj4wxGgVT14GyBg/KVX8 ai66gKL6f6ImKXoJi1w9/lrFrsZ0ccoSf6jYoD8E= From: Laurent Pinchart To: libcamera-devel@lists.libcamera.org Date: Wed, 10 Jul 2019 22:17:03 +0300 Message-Id: <20190710191708.13049-1-laurent.pinchart@ideasonboard.com> X-Mailer: git-send-email 2.21.0 MIME-Version: 1.0 Subject: [libcamera-devel] [PATCH 1/6] libcamera: Add thread support X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.23 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Wed, 10 Jul 2019 19:17:42 -0000 The new Thread class wraps std::thread in order to integrate it with the Object, Signal and EventDispatcher classes. By default new threads run an internal event loop, and their run() method can be overloaded to provide a custom thread loop. Signed-off-by: Laurent Pinchart Reviewed-by: Niklas Söderlund --- include/libcamera/camera_manager.h | 2 - src/libcamera/camera_manager.cpp | 15 +- src/libcamera/include/thread.h | 61 ++++++ src/libcamera/meson.build | 3 + src/libcamera/thread.cpp | 335 +++++++++++++++++++++++++++++ 5 files changed, 403 insertions(+), 13 deletions(-) create mode 100644 src/libcamera/include/thread.h create mode 100644 src/libcamera/thread.cpp diff --git a/include/libcamera/camera_manager.h b/include/libcamera/camera_manager.h index 633d27d17ebf..0e8881baba40 100644 --- a/include/libcamera/camera_manager.h +++ b/include/libcamera/camera_manager.h @@ -46,8 +46,6 @@ private: std::vector> pipes_; std::vector> cameras_; - std::unique_ptr dispatcher_; - static const std::string version_; }; diff --git a/src/libcamera/camera_manager.cpp b/src/libcamera/camera_manager.cpp index 337496c21cfc..2cf014233b05 100644 --- a/src/libcamera/camera_manager.cpp +++ b/src/libcamera/camera_manager.cpp @@ -14,6 +14,7 @@ #include "event_dispatcher_poll.h" #include "log.h" #include "pipeline_handler.h" +#include "thread.h" #include "utils.h" /** @@ -56,7 +57,7 @@ LOG_DEFINE_CATEGORY(Camera) */ CameraManager::CameraManager() - : enumerator_(nullptr), dispatcher_(nullptr) + : enumerator_(nullptr) { } @@ -247,12 +248,7 @@ CameraManager *CameraManager::instance() */ void CameraManager::setEventDispatcher(std::unique_ptr dispatcher) { - if (dispatcher_) { - LOG(Camera, Warning) << "Event dispatcher is already set"; - return; - } - - dispatcher_ = std::move(dispatcher); + Thread::current()->setEventDispatcher(std::move(dispatcher)); } /** @@ -268,10 +264,7 @@ void CameraManager::setEventDispatcher(std::unique_ptr dispatch */ EventDispatcher *CameraManager::eventDispatcher() { - if (!dispatcher_) - dispatcher_ = utils::make_unique(); - - return dispatcher_.get(); + return Thread::current()->eventDispatcher(); } } /* namespace libcamera */ diff --git a/src/libcamera/include/thread.h b/src/libcamera/include/thread.h new file mode 100644 index 000000000000..e881d90e9367 --- /dev/null +++ b/src/libcamera/include/thread.h @@ -0,0 +1,61 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2019, Google Inc. + * + * thread.h - Thread support + */ +#ifndef __LIBCAMERA_THREAD_H__ +#define __LIBCAMERA_THREAD_H__ + +#include +#include +#include + +#include + +namespace libcamera { + +class EventDispatcher; +class ThreadData; +class ThreadMain; + +using Mutex = std::mutex; +using MutexLocker = std::unique_lock; + +class Thread +{ +public: + Thread(); + virtual ~Thread(); + + void start(); + void exit(int code = 0); + void wait(); + + bool isRunning(); + + Signal finished; + + static Thread *current(); + + EventDispatcher *eventDispatcher(); + void setEventDispatcher(std::unique_ptr dispatcher); + +protected: + int exec(); + virtual void run(); + +private: + void startThread(); + void finishThread(); + + friend class ThreadData; + friend class ThreadMain; + + std::thread thread_; + ThreadData *data_; +}; + +} /* namespace libcamera */ + +#endif /* __LIBCAMERA_THREAD_H__ */ diff --git a/src/libcamera/meson.build b/src/libcamera/meson.build index 97ff86e2167f..bf71524f768c 100644 --- a/src/libcamera/meson.build +++ b/src/libcamera/meson.build @@ -23,6 +23,7 @@ libcamera_sources = files([ 'request.cpp', 'signal.cpp', 'stream.cpp', + 'thread.cpp', 'timer.cpp', 'utils.cpp', 'v4l2_controls.cpp', @@ -45,6 +46,7 @@ libcamera_headers = files([ 'include/media_device.h', 'include/media_object.h', 'include/pipeline_handler.h', + 'include/thread.h', 'include/utils.h', 'include/v4l2_device.h', 'include/v4l2_subdevice.h', @@ -91,6 +93,7 @@ libcamera_sources += version_cpp libcamera_deps = [ cc.find_library('dl'), libudev, + dependency('threads'), ] libcamera = shared_library('camera', diff --git a/src/libcamera/thread.cpp b/src/libcamera/thread.cpp new file mode 100644 index 000000000000..95636ecaab53 --- /dev/null +++ b/src/libcamera/thread.cpp @@ -0,0 +1,335 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2019, Google Inc. + * + * thread.cpp - Thread support + */ + +#include "thread.h" + +#include + +#include + +#include "event_dispatcher_poll.h" +#include "log.h" + +/** + * \file thread.h + * \brief Thread support + */ + +namespace libcamera { + +LOG_DEFINE_CATEGORY(Thread) + +class ThreadMain; + +/** + * \brief Thread-local internal data + */ +class ThreadData +{ +public: + ThreadData() + : thread_(nullptr), running_(false), dispatcher_(nullptr) + { + } + + static ThreadData *current(); + +private: + friend class Thread; + friend class ThreadMain; + + Thread *thread_; + bool running_; + + Mutex mutex_; + + std::atomic dispatcher_; + + std::atomic exit_; + int exitCode_; +}; + +/** + * \brief Thread wrapper for the main thread + */ +class ThreadMain : public Thread +{ +public: + ThreadMain() + { + data_->running_ = true; + } + +protected: + void run() override + { + LOG(Thread, Fatal) << "The main thread can't be restarted"; + } +}; + +static thread_local ThreadData *currentThreadData = nullptr; +static ThreadMain mainThread; + +/** + * \brief Retrieve thread-local internal data for the current thread + * \return The thread-local internal data for the current thread + */ +ThreadData *ThreadData::current() +{ + if (currentThreadData) + return currentThreadData; + + /* + * The main thread doesn't receive thread-local data when it is + * started, set it here. + */ + ThreadData *data = mainThread.data_; + currentThreadData = data; + return data; +} + +/** + * \typedef Mutex + * \brief An alias for std::mutex + */ + +/** + * \typedef MutexLocker + * \brief An alias for std::unique_lock + */ + +/** + * \class Thread + * \brief A thread of execution + * + * The Thread class is a wrapper around std::thread that handles integration + * with the Object, Signal and EventDispatcher classes. + * + * Thread instances by default run an event loop until the exit() method is + * called. A custom event dispatcher may be installed with + * setEventDispatcher(), otherwise a poll-based event dispatcher is used. This + * behaviour can be overriden by overloading the run() method. + */ + +/** + * \brief Create a thread + */ +Thread::Thread() +{ + data_ = new ThreadData; + data_->thread_ = this; +} + +Thread::~Thread() +{ + delete data_->dispatcher_.load(std::memory_order_relaxed); + delete data_; +} + +/** + * \brief Start the thread + */ +void Thread::start() +{ + MutexLocker locker(data_->mutex_); + + if (data_->running_) + return; + + data_->running_ = true; + data_->exitCode_ = -1; + data_->exit_.store(false, std::memory_order_relaxed); + + thread_ = std::thread(&Thread::startThread, this); +} + +void Thread::startThread() +{ + struct ThreadCleaner { + ThreadCleaner(Thread *thread, void (Thread::*cleaner)()) + : thread_(thread), cleaner_(cleaner) + { + } + ~ThreadCleaner() + { + (thread_->*cleaner_)(); + } + + Thread *thread_; + void (Thread::*cleaner_)(); + }; + + /* + * Make sure the thread is cleaned up even if the run method exits + * abnormally (for instance via a direct call to pthread_cancel()). + */ + thread_local ThreadCleaner cleaner(this, &Thread::finishThread); + + currentThreadData = data_; + + run(); +} + +/** + * \brief Enter the event loop + * + * This method enter an event loop based on the event dispatcher instance for + * the thread, and blocks until the exit() method is called. It is meant to be + * called within the thread from the run() method and shall not be called + * outside of the thread. + * + * \return The exit code passed to the exit() method + */ +int Thread::exec() +{ + MutexLocker locker(data_->mutex_); + + EventDispatcher *dispatcher = eventDispatcher(); + + locker.unlock(); + + while (!data_->exit_.load(std::memory_order_acquire)) + dispatcher->processEvents(); + + locker.lock(); + + return data_->exitCode_; +} + +/** + * \brief Main method of the thread + * + * When the thread is started with start(), it calls this method in the context + * of the new thread. The run() method can be overloaded to perform custom + * work. When this method returns the thread execution is stopped, and the \ref + * finished signal is emitted. + * + * The base implementation just calls exec(). + */ +void Thread::run() +{ + exec(); +} + +void Thread::finishThread() +{ + data_->mutex_.lock(); + data_->running_ = false; + data_->mutex_.unlock(); + + finished.emit(this); +} + +/** + * \brief Stop the thread's event loop + * \param[in] code The exit code + * + * This method interrupts the event loop started by the exec() method, causing + * exec() to return \a code. + * + * Calling exit() on a thread that reimplements the run() method and doesn't + * call exec() will likely have no effect. + */ +void Thread::exit(int code) +{ + data_->exitCode_ = code; + data_->exit_.store(true, std::memory_order_release); + + EventDispatcher *dispatcher = data_->dispatcher_.load(std::memory_order_relaxed); + if (!dispatcher) + return; + + dispatcher->interrupt(); +} + +/** + * \brief Wait for the thread to finish + * + * This method waits until the thread finishes, or returns immediately if the + * thread is not running. + */ +void Thread::wait() +{ + if (thread_.joinable()) + thread_.join(); +} + +/** + * \brief Check if the thread is running + * + * A Thread instance is considered as running once the underlying thread has + * started. This method guarantees that it returns true after the start() + * method returns, and false after the wait() method returns. + * + * \return True if the thread is running, false otherwise + */ +bool Thread::isRunning() +{ + MutexLocker locker(data_->mutex_); + return data_->running_; +} + +/** + * \var Thread::finished + * \brief Signal the end of thread execution + */ + +/** + * \brief Retrieve the Thread instance for the current thread + * \return The Thread instance for the current thread + */ +Thread *Thread::current() +{ + ThreadData *data = ThreadData::current(); + return data->thread_; +} + +/** + * \brief Set the event dispatcher + * \param[in] dispatcher Pointer to the event dispatcher + * + * Threads that run an event loop require an event dispatcher to integrate + * event notification and timers with the loop. Users that want to provide + * their own event dispatcher shall call this method once and only once before + * the thread is started with start(). If no event dispatcher is provided, a + * default poll-based implementation will be used. + * + * The Thread takes ownership of the event dispatcher and will delete it when + * the thread is destroyed. + */ +void Thread::setEventDispatcher(std::unique_ptr dispatcher) +{ + if (data_->dispatcher_.load(std::memory_order_relaxed)) { + LOG(Thread, Warning) << "Event dispatcher is already set"; + return; + } + + data_->dispatcher_.store(dispatcher.release(), + std::memory_order_relaxed); +} + +/** + * \brief Retrieve the event dispatcher + * + * This method retrieves the event dispatcher set with setEventDispatcher(). + * If no dispatcher has been set, a default poll-based implementation is created + * and returned, and no custom event dispatcher may be installed anymore. + * + * The returned event dispatcher is valid until the thread is destroyed. + * + * \return Pointer to the event dispatcher + */ +EventDispatcher *Thread::eventDispatcher() +{ + if (!data_->dispatcher_.load(std::memory_order_relaxed)) + data_->dispatcher_.store(new EventDispatcherPoll(), + std::memory_order_release); + + return data_->dispatcher_.load(std::memory_order_relaxed); +} + +}; /* namespace libcamera */ From patchwork Wed Jul 10 19:17:04 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Laurent Pinchart X-Patchwork-Id: 1645 Return-Path: Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [IPv6:2001:4b98:dc2:55:216:3eff:fef7:d647]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 7801B61572 for ; Wed, 10 Jul 2019 21:17:43 +0200 (CEST) Received: from pendragon.ideasonboard.com (softbank126163157105.bbtec.net [126.163.157.105]) by perceval.ideasonboard.com (Postfix) with ESMTPSA id 02D2331C for ; Wed, 10 Jul 2019 21:17:41 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1562786263; bh=rEU0TzQtsx7Avmm59bpHObj3T0geLBxsY5s8gJnJA/k=; h=From:To:Subject:Date:In-Reply-To:References:From; b=Xug+i72VWv7f6QwRzHzKSVPzByTnMRd07KwpF631+oBteMJY4y5UBx1ySme4m4rI+ NJBkEfGFpgKIv8s9gYzjYK5Bb1jPamNCcDjCGNsnqJRlEdr689UAYir9RlBLS+YcBs Esrn7X+VjYssE790OxuYaCd9JswPhtypOiyA3Qf8= From: Laurent Pinchart To: libcamera-devel@lists.libcamera.org Date: Wed, 10 Jul 2019 22:17:04 +0300 Message-Id: <20190710191708.13049-2-laurent.pinchart@ideasonboard.com> X-Mailer: git-send-email 2.21.0 In-Reply-To: <20190710191708.13049-1-laurent.pinchart@ideasonboard.com> References: <20190710191708.13049-1-laurent.pinchart@ideasonboard.com> MIME-Version: 1.0 Subject: [libcamera-devel] [PATCH 2/6] libcamera: thread: Add a messaging passing API X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.23 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Wed, 10 Jul 2019 19:17:43 -0000 Create a new Message class to model a message that can be passed to an object living in another thread. Only an invalid message type is currently defined, more messages will be added in the future. The Thread class is extended with a messages queue, and the Object class with thread affinity. Signed-off-by: Laurent Pinchart Reviewed-by: Niklas Söderlund --- include/libcamera/object.h | 13 +++ src/libcamera/include/message.h | 37 ++++++++ src/libcamera/include/thread.h | 9 ++ src/libcamera/meson.build | 2 + src/libcamera/message.cpp | 71 +++++++++++++++ src/libcamera/object.cpp | 77 ++++++++++++++++- src/libcamera/thread.cpp | 147 +++++++++++++++++++++++++++++++- 7 files changed, 354 insertions(+), 2 deletions(-) create mode 100644 src/libcamera/include/message.h create mode 100644 src/libcamera/message.cpp diff --git a/include/libcamera/object.h b/include/libcamera/object.h index eadd41f9a41f..d61dfb1ebaef 100644 --- a/include/libcamera/object.h +++ b/include/libcamera/object.h @@ -8,26 +8,39 @@ #define __LIBCAMERA_OBJECT_H__ #include +#include namespace libcamera { +class Message; class SignalBase; template class Signal; +class Thread; class Object { public: + Object(); virtual ~Object(); + void postMessage(std::unique_ptr msg); + virtual void message(Message *msg); + + Thread *thread() const { return thread_; } + void moveToThread(Thread *thread); + private: template friend class Signal; + friend class Thread; void connect(SignalBase *signal); void disconnect(SignalBase *signal); + Thread *thread_; std::list signals_; + unsigned int pendingMessages_; }; }; /* namespace libcamera */ diff --git a/src/libcamera/include/message.h b/src/libcamera/include/message.h new file mode 100644 index 000000000000..97c9b80ec0e0 --- /dev/null +++ b/src/libcamera/include/message.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2019, Google Inc. + * + * message.h - Message queue support + */ +#ifndef __LIBCAMERA_MESSAGE_H__ +#define __LIBCAMERA_MESSAGE_H__ + +namespace libcamera { + +class Object; +class Thread; + +class Message +{ +public: + enum Type { + None = 0, + }; + + Message(Type type); + virtual ~Message(); + + Type type() const { return type_; } + Object *receiver() const { return receiver_; } + +private: + friend class Thread; + + Type type_; + Object *receiver_; +}; + +} /* namespace libcamera */ + +#endif /* __LIBCAMERA_MESSAGE_H__ */ diff --git a/src/libcamera/include/thread.h b/src/libcamera/include/thread.h index e881d90e9367..acae91cb6457 100644 --- a/src/libcamera/include/thread.h +++ b/src/libcamera/include/thread.h @@ -16,6 +16,8 @@ namespace libcamera { class EventDispatcher; +class Message; +class Object; class ThreadData; class ThreadMain; @@ -49,9 +51,16 @@ private: void startThread(); void finishThread(); + void postMessage(std::unique_ptr msg, Object *receiver); + void removeMessages(Object *receiver); + void dispatchMessages(); + + friend class Object; friend class ThreadData; friend class ThreadMain; + void moveObject(Object *object); + std::thread thread_; ThreadData *data_; }; diff --git a/src/libcamera/meson.build b/src/libcamera/meson.build index bf71524f768c..3e5097a4cdc7 100644 --- a/src/libcamera/meson.build +++ b/src/libcamera/meson.build @@ -18,6 +18,7 @@ libcamera_sources = files([ 'log.cpp', 'media_device.cpp', 'media_object.cpp', + 'message.cpp', 'object.cpp', 'pipeline_handler.cpp', 'request.cpp', @@ -45,6 +46,7 @@ libcamera_headers = files([ 'include/log.h', 'include/media_device.h', 'include/media_object.h', + 'include/message.h', 'include/pipeline_handler.h', 'include/thread.h', 'include/utils.h', diff --git a/src/libcamera/message.cpp b/src/libcamera/message.cpp new file mode 100644 index 000000000000..47caf44dc82d --- /dev/null +++ b/src/libcamera/message.cpp @@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +/* + * Copyright (C) 2019, Google Inc. + * + * message.cpp - Message queue support + */ + +#include "message.h" + +#include "log.h" + +/** + * \file message.h + * \brief Message queue support + * + * The messaging API enables inter-thread communication through message + * posting. Messages can be sent from any thread to any recipient deriving from + * the Object class. + * + * The post a message, the sender allocates it dynamically as instance of a + * class derived from Message. It then posts the message to an Object recipient + * through Object::postMessage(). Message ownership is passed to the object, + * the message shall thus not store any temporary data. + * + * The message is delivered in the context of the object's thread, through the + * Object::message() virtual method. After delivery the message is + * automatically deleted. + */ + +namespace libcamera { + +LOG_DEFINE_CATEGORY(Message) + +/** + * \class Message + * \brief A message that can be posted to a Thread + */ + +/** + * \enum Message::Type + * \brief The message type + * \var Message::None + * \brief Invalid message type + */ + +/** + * \brief Construct a message object of type \a type + * \param[in] type The message type + */ +Message::Message(Message::Type type) + : type_(type) +{ +} + +Message::~Message() +{ +} + +/** + * \fn Message::type() + * \brief Retrieve the message type + * \return The message type + */ + +/** + * \fn Message::receiver() + * \brief Retrieve the message receiver + * \return The message receiver + */ + +}; /* namespace libcamera */ diff --git a/src/libcamera/object.cpp b/src/libcamera/object.cpp index a504ca2c9daf..695e6c11b3a4 100644 --- a/src/libcamera/object.cpp +++ b/src/libcamera/object.cpp @@ -9,6 +9,9 @@ #include +#include "log.h" +#include "thread.h" + /** * \file object.h * \brief Base object to support automatic signal disconnection @@ -24,13 +27,85 @@ namespace libcamera { * slots. By inheriting from Object, an object is automatically disconnected * from all connected signals when it gets destroyed. * - * \sa Signal + * Object instance are bound to the thread in which they're created. When a + * message is posted to an object, its handler will run in the object's thread. + * This allows implementing easy message passing between threads by inheriting + * from the Object class. + * + * \sa Message, Signal, Thread */ +Object::Object() + : pendingMessages_(0) +{ + thread_ = Thread::current(); +} + Object::~Object() { for (SignalBase *signal : signals_) signal->disconnect(this); + + if (pendingMessages_) + thread()->removeMessages(this); +} + +/** + * \brief Post a message to the object's thread + * \param[in] msg The message + * + * This method posts the message \a msg to the message queue of the object's + * thread, to be delivered to the object through the message() method in the + * context of its thread. Message ownership is passed to the thread, and the + * message will be deleted after being delivered. + * + * Messages are delivered through the thread's event loop. If the thread is not + * running its event loop the message will not be delivered until the event + * loop gets started. + */ +void Object::postMessage(std::unique_ptr msg) +{ + thread()->postMessage(std::move(msg), this); +} + +/** + * \brief Message handler for the object + * \param[in] msg The message + * + * This virtual method receives messages for the object. It is called in the + * context of the object's thread, and can be overridden to process custom + * messages. The parent QObject::message() method shall be called for any + * message not handled by the override method. + * + * The message \a msg is valid only for the duration of the call, no reference + * to it shall be kept after this method returns. + */ +void Object::message(Message *msg) +{ +} + +/** + * \fn Object::thread() + * \brief Retrieve the thread the object is bound to + * \return The thread the object is bound to + */ + +/** + * \brief Move the object to a different thread + * \param[in] thread The target thread + * + * This method moves the object from the current thread to the new \a thread. + * It shall be called from the thread in which the object currently lives, + * otherwise the behaviour is undefined. + */ +void Object::moveToThread(Thread *thread) +{ + ASSERT(Thread::current() == thread_); + + if (thread_ == thread) + return; + + thread->moveObject(this); } void Object::connect(SignalBase *signal) diff --git a/src/libcamera/thread.cpp b/src/libcamera/thread.cpp index 95636ecaab53..5d46eeb8d3a5 100644 --- a/src/libcamera/thread.cpp +++ b/src/libcamera/thread.cpp @@ -8,11 +8,13 @@ #include "thread.h" #include +#include #include #include "event_dispatcher_poll.h" #include "log.h" +#include "message.h" /** * \file thread.h @@ -25,6 +27,22 @@ LOG_DEFINE_CATEGORY(Thread) class ThreadMain; +/** + * \brief A queue of posted messages + */ +class MessageQueue +{ +public: + /** + * \brief List of queued Message instances + */ + std::list> list_; + /** + * \brief Protects the \ref list_ + */ + Mutex mutex_; +}; + /** * \brief Thread-local internal data */ @@ -51,6 +69,8 @@ private: std::atomic exit_; int exitCode_; + + MessageQueue messages_; }; /** @@ -192,8 +212,10 @@ int Thread::exec() locker.unlock(); - while (!data_->exit_.load(std::memory_order_acquire)) + while (!data_->exit_.load(std::memory_order_acquire)) { + dispatchMessages(); dispatcher->processEvents(); + } locker.lock(); @@ -332,4 +354,127 @@ EventDispatcher *Thread::eventDispatcher() return data_->dispatcher_.load(std::memory_order_relaxed); } +/** + * \brief Post a message to the thread for the \a receiver + * \param[in] msg The message + * \param[in] receiver The receiver + * + * This method stores the message \a msg in the message queue of the thread for + * the \a receiver and wake up the thread's event loop. Message ownership is + * passed to the thread, and the message will be deleted after being delivered. + * + * Messages are delivered through the thread's event loop. If the thread is not + * running its event loop the message will not be delivered until the event + * loop gets started. + * + * If the \a receiver is not bound to this thread the behaviour is undefined. + * + * \sa exec() + */ +void Thread::postMessage(std::unique_ptr msg, Object *receiver) +{ + msg->receiver_ = receiver; + + ASSERT(data_ == receiver->thread()->data_); + + MutexLocker locker(data_->messages_.mutex_); + data_->messages_.list_.push_back(std::move(msg)); + receiver->pendingMessages_++; + locker.unlock(); + + EventDispatcher *dispatcher = + data_->dispatcher_.load(std::memory_order_acquire); + if (dispatcher) + dispatcher->interrupt(); +} + +/** + * \brief Remove all posted messages for the \a receiver + * \param[in] receiver The receiver + * + * If the \a receiver is not bound to this thread the behaviour is undefined. + */ +void Thread::removeMessages(Object *receiver) +{ + ASSERT(data_ == receiver->thread()->data_); + + MutexLocker locker(data_->messages_.mutex_); + if (!receiver->pendingMessages_) + return; + + std::vector> toDelete; + for (std::unique_ptr &msg : data_->messages_.list_) { + if (!msg) + continue; + if (msg->receiver_ != receiver) + continue; + + /* + * Move the message to the pending deletion list to delete it + * after releasing the lock. The messages list element will + * contain a null pointer, and will be removed when dispatching + * messages. + */ + toDelete.push_back(std::move(msg)); + receiver->pendingMessages_--; + } + + ASSERT(!receiver->pendingMessages_); + locker.unlock(); + + toDelete.clear(); +} + +/** + * \brief Dispatch all posted messages for this thread + */ +void Thread::dispatchMessages() +{ + MutexLocker locker(data_->messages_.mutex_); + + while (!data_->messages_.list_.empty()) { + std::unique_ptr msg = std::move(data_->messages_.list_.front()); + data_->messages_.list_.pop_front(); + if (!msg) + continue; + + Object *receiver = msg->receiver_; + ASSERT(data_ == receiver->thread()->data_); + + locker.unlock(); + receiver->message(msg.get()); + locker.lock(); + + receiver->pendingMessages_--; + } +} + +/** + * \brief Move an \a object to the thread + * \param[in] object The object + */ +void Thread::moveObject(Object *object) +{ + ThreadData *currentData = object->thread_->data_; + ThreadData *targetData = data_; + + MutexLocker lockerFrom(currentData->mutex_, std::defer_lock); + MutexLocker lockerTo(targetData->mutex_, std::defer_lock); + std::lock(lockerFrom, lockerTo); + + /* Move pending messages to the message queue of the new thread. */ + if (object->pendingMessages_) { + for (std::unique_ptr &msg : currentData->messages_.list_) { + if (!msg) + continue; + if (msg->receiver_ != object) + continue; + + targetData->messages_.list_.push_back(std::move(msg)); + } + } + + object->thread_ = this; +} + }; /* namespace libcamera */ From patchwork Wed Jul 10 19:17:05 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Laurent Pinchart X-Patchwork-Id: 1646 Return-Path: Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [IPv6:2001:4b98:dc2:55:216:3eff:fef7:d647]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 10DD261575 for ; Wed, 10 Jul 2019 21:17:45 +0200 (CEST) Received: from pendragon.ideasonboard.com (softbank126163157105.bbtec.net [126.163.157.105]) by perceval.ideasonboard.com (Postfix) with ESMTPSA id D016B31C for ; Wed, 10 Jul 2019 21:17:43 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1562786264; bh=taA4zZl5SZX1QHjkNWVgkjPKNlIHP10+mCstO3jRTs4=; h=From:To:Subject:Date:In-Reply-To:References:From; b=oBYuw3q5TIqLdUVum4Pwqc6M8+wniSepRIEPpeiITpkziooP+539tlQorEZ6NU9tE iBZ/fsNH9gwt/nhaO/iQaBnz9zf7mN1+CoCYXzHTyY0ST5MtX/bw/MmXAzKk6ezM++ Ke6l5WjmeQb/qvGCXmCDyg/HH0cvPw/lqcSr3nFY= From: Laurent Pinchart To: libcamera-devel@lists.libcamera.org Date: Wed, 10 Jul 2019 22:17:05 +0300 Message-Id: <20190710191708.13049-3-laurent.pinchart@ideasonboard.com> X-Mailer: git-send-email 2.21.0 In-Reply-To: <20190710191708.13049-1-laurent.pinchart@ideasonboard.com> References: <20190710191708.13049-1-laurent.pinchart@ideasonboard.com> MIME-Version: 1.0 Subject: [libcamera-devel] [PATCH 3/6] libcamera: signal: Support cross-thread signals X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.23 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Wed, 10 Jul 2019 19:17:45 -0000 Allow signals to cross thread boundaries by posting them to the recipient through messages instead of calling the slot directly when the recipient lives in a different thread. Signed-off-by: Laurent Pinchart Reviewed-by: Niklas Söderlund --- include/libcamera/signal.h | 70 +++++++++++++++++++++++++++++---- src/libcamera/include/message.h | 14 +++++++ src/libcamera/message.cpp | 22 +++++++++++ src/libcamera/object.cpp | 15 +++++++ src/libcamera/signal.cpp | 26 ++++++++++++ 5 files changed, 139 insertions(+), 8 deletions(-) diff --git a/include/libcamera/signal.h b/include/libcamera/signal.h index c8f3243eaf5a..04e8fe7eebe3 100644 --- a/include/libcamera/signal.h +++ b/include/libcamera/signal.h @@ -8,6 +8,8 @@ #define __LIBCAMERA_SIGNAL_H__ #include +#include +#include #include #include @@ -16,6 +18,9 @@ namespace libcamera { template class Signal; +class SlotBase; +template +class SlotArgs; class SlotBase { @@ -27,6 +32,9 @@ public: void *obj() { return obj_; } bool isObject() const { return isObject_; } + void activatePack(void *pack); + virtual void invokePack(void *pack) = 0; + protected: void *obj_; bool isObject_; @@ -35,24 +43,70 @@ protected: template class SlotArgs : public SlotBase { +private: +#ifndef __DOXYGEN__ + /* + * This is a cheap partial implementation of std::integer_sequence<> + * from C++14. + */ + template + struct sequence { + }; + + template + struct generator : generator { + }; + + template + struct generator<0, S...> { + typedef sequence type; + }; +#endif + public: + using PackType = std::tuple::type...>; + SlotArgs(void *obj, bool isObject) : SlotBase(obj, isObject) {} + void invokePack(void *pack) override + { + invokePack(pack, typename generator::type()); + } + + template + void invokePack(void *pack, sequence) + { + PackType *args = static_cast(pack); + invoke(std::get(*args)...); + delete args; + } + + virtual void activate(Args... args) = 0; virtual void invoke(Args... args) = 0; - -protected: - friend class Signal; }; template class SlotMember : public SlotArgs { public: + using PackType = std::tuple::type...>; + SlotMember(T *obj, bool isObject, void (T::*func)(Args...)) : SlotArgs(obj, isObject), func_(func) {} - void invoke(Args... args) { (static_cast(this->obj_)->*func_)(args...); } + void activate(Args... args) + { + if (this->isObject_) + SlotBase::activatePack(new PackType{ args... }); + else + (static_cast(this->obj_)->*func_)(args...); + } + + void invoke(Args... args) + { + (static_cast(this->obj_)->*func_)(args...); + } private: friend class Signal; @@ -66,7 +120,8 @@ public: SlotStatic(void (*func)(Args...)) : SlotArgs(nullptr, false), func_(func) {} - void invoke(Args... args) { (*func_)(args...); } + void activate(Args... args) { (*func_)(args...); } + void invoke(Args... args) {} private: friend class Signal; @@ -186,9 +241,8 @@ public: * disconnect operation, invalidating the iterator. */ std::vector slots{ slots_.begin(), slots_.end() }; - for (SlotBase *slot : slots) { - static_cast *>(slot)->invoke(args...); - } + for (SlotBase *slot : slots) + static_cast *>(slot)->activate(args...); } }; diff --git a/src/libcamera/include/message.h b/src/libcamera/include/message.h index 97c9b80ec0e0..db17d647c280 100644 --- a/src/libcamera/include/message.h +++ b/src/libcamera/include/message.h @@ -10,6 +10,7 @@ namespace libcamera { class Object; +class SlotBase; class Thread; class Message @@ -17,6 +18,7 @@ class Message public: enum Type { None = 0, + SignalMessage = 1, }; Message(Type type); @@ -32,6 +34,18 @@ private: Object *receiver_; }; +class SignalMessage : public Message +{ +public: + SignalMessage(SlotBase *slot, void *pack) + : Message(Message::SignalMessage), slot_(slot), pack_(pack) + { + } + + SlotBase *slot_; + void *pack_; +}; + } /* namespace libcamera */ #endif /* __LIBCAMERA_MESSAGE_H__ */ diff --git a/src/libcamera/message.cpp b/src/libcamera/message.cpp index 47caf44dc82d..66dd1e8bd618 100644 --- a/src/libcamera/message.cpp +++ b/src/libcamera/message.cpp @@ -68,4 +68,26 @@ Message::~Message() * \return The message receiver */ +/** + * \class SignalMessage + * \brief A message carrying a Signal across threads + */ + +/** + * \fn SignalMessage::SignalMessage() + * \brief Construct a SignalMessage + * \param[in] slot The slot that the signal targets + * \param[in] pack The signal arguments + */ + +/** + * \var SignalMessage::slot_ + * \brief The slot that the signal targets + */ + +/** + * \var SignalMessage::pack_ + * \brief The signal arguments + */ + }; /* namespace libcamera */ diff --git a/src/libcamera/object.cpp b/src/libcamera/object.cpp index 695e6c11b3a4..1dfa159267fe 100644 --- a/src/libcamera/object.cpp +++ b/src/libcamera/object.cpp @@ -10,6 +10,7 @@ #include #include "log.h" +#include "message.h" #include "thread.h" /** @@ -32,6 +33,10 @@ namespace libcamera { * This allows implementing easy message passing between threads by inheriting * from the Object class. * + * Object slots connected to signals will also run in the context of the + * object's thread, regardless of whether the signal is emitted in the same or + * in another thread. + * * \sa Message, Signal, Thread */ @@ -82,6 +87,16 @@ void Object::postMessage(std::unique_ptr msg) */ void Object::message(Message *msg) { + switch (msg->type()) { + case Message::SignalMessage: { + SignalMessage *smsg = static_cast(msg); + smsg->slot_->invokePack(smsg->pack_); + break; + } + + default: + break; + } } /** diff --git a/src/libcamera/signal.cpp b/src/libcamera/signal.cpp index 4cb85ecb0686..53c18535fee3 100644 --- a/src/libcamera/signal.cpp +++ b/src/libcamera/signal.cpp @@ -7,6 +7,10 @@ #include +#include "message.h" +#include "thread.h" +#include "utils.h" + /** * \file signal.h * \brief Signal & slot implementation @@ -42,8 +46,30 @@ namespace libcamera { * to the same slot. Duplicate connections between a signal and a slot are * allowed and result in the slot being called multiple times for the same * signal emission. + * + * When a slot belongs to an instance of the Object class, the slot is called + * in the context of the thread that the object is bound to. If the signal is + * emitted from the same thread, the slot will be called synchronously, before + * Signal::emit() returns. If the signal is emitted from a different thread, + * the slot will be called asynchronously from the object's thread's event + * loop, after the Signal::emit() method returns, with a copy of the signal's + * arguments. The emitter shall thus ensure that any pointer or reference + * passed through the signal will remain valid after the signal is emitted. */ +void SlotBase::activatePack(void *pack) +{ + Object *obj = static_cast(obj_); + + if (Thread::current() == obj->thread()) { + invokePack(pack); + } else { + std::unique_ptr msg = + utils::make_unique(this, pack); + obj->postMessage(std::move(msg)); + } +} + /** * \fn Signal::connect(T *object, void(T::*func)(Args...)) * \brief Connect the signal to a member function slot From patchwork Wed Jul 10 19:17:06 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Laurent Pinchart X-Patchwork-Id: 1647 Return-Path: Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [IPv6:2001:4b98:dc2:55:216:3eff:fef7:d647]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 882BF6157B for ; Wed, 10 Jul 2019 21:17:46 +0200 (CEST) Received: from pendragon.ideasonboard.com (softbank126163157105.bbtec.net [126.163.157.105]) by perceval.ideasonboard.com (Postfix) with ESMTPSA id 5E75354B for ; Wed, 10 Jul 2019 21:17:45 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1562786266; bh=nClxrVfSMwnbHVqa+iOoMRsPGU5WwfEC/3Y5sbTELjA=; h=From:To:Subject:Date:In-Reply-To:References:From; b=G8ui7RpwGFkdAVs2gkFyuPceDu9wDI91B8VQdZg5jnSXxtVZbRp5k1h872jdYtzwX Ag+NCYFmJ8ZjzvGwTk6SfcZPbbc61KQRLT1HzYqqDfl+V2Hg2tPNbHCAMk+zX274fc judFnB4tn0XuUrmeH+T4LRBrQKsmzPid3cDnW3os= From: Laurent Pinchart To: libcamera-devel@lists.libcamera.org Date: Wed, 10 Jul 2019 22:17:06 +0300 Message-Id: <20190710191708.13049-4-laurent.pinchart@ideasonboard.com> X-Mailer: git-send-email 2.21.0 In-Reply-To: <20190710191708.13049-1-laurent.pinchart@ideasonboard.com> References: <20190710191708.13049-1-laurent.pinchart@ideasonboard.com> MIME-Version: 1.0 Subject: [libcamera-devel] [PATCH 4/6] test: Add Thread test cases X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.23 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Wed, 10 Jul 2019 19:17:46 -0000 The Thread test case verifies that - a Thread instance is created for the main thread - a new Thread can be created, started, and stopped Signed-off-by: Laurent Pinchart Reviewed-by: Niklas Söderlund --- test/meson.build | 1 + test/threads.cpp | 93 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 test/threads.cpp diff --git a/test/meson.build b/test/meson.build index 41b54ffd358c..bd0e0d98f0e7 100644 --- a/test/meson.build +++ b/test/meson.build @@ -21,6 +21,7 @@ public_tests = [ internal_tests = [ ['camera-sensor', 'camera-sensor.cpp'], + ['threads', 'threads.cpp'], ] foreach t : public_tests diff --git a/test/threads.cpp b/test/threads.cpp new file mode 100644 index 000000000000..9a2d39dfd106 --- /dev/null +++ b/test/threads.cpp @@ -0,0 +1,93 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2019, Google Inc. + * + * threads.cpp - Threads test + */ + +#include +#include +#include + +#include "thread.h" +#include "test.h" + +using namespace std; +using namespace libcamera; + +class InstrumentedThread : public Thread +{ +public: + InstrumentedThread(unsigned int iterations) + : iterations_(iterations) + { + } + +protected: + void run() + { + for (unsigned int i = 0; i < iterations_; ++i) { + this_thread::sleep_for(chrono::milliseconds(50)); + } + } + +private: + unsigned int iterations_; +}; + +class ThreadTest : public Test +{ +protected: + int init() + { + return 0; + } + + int run() + { + /* Test Thread() retrieval for the main thread. */ + Thread *thread = Thread::current(); + if (!thread) { + cout << "Thread::current() failed to main thread" + << endl; + return TestFail; + } + + if (!thread->isRunning()) { + cout << "Main thread is not running" << endl; + return TestFail; + } + + /* Test starting the main thread, the test shall not crash. */ + thread->start(); + + /* Test the running state of a custom thread. */ + thread = new Thread(); + thread->start(); + + if (!thread->isRunning()) { + cout << "Thread is not running after being started" + << endl; + return TestFail; + } + + thread->exit(0); + thread->wait(); + + if (thread->isRunning()) { + cout << "Thread is still running after finishing" + << endl; + return TestFail; + } + + delete thread; + + return TestPass; + } + + void cleanup() + { + } +}; + +TEST_REGISTER(ThreadTest) From patchwork Wed Jul 10 19:17:07 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Laurent Pinchart X-Patchwork-Id: 1648 Return-Path: Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [IPv6:2001:4b98:dc2:55:216:3eff:fef7:d647]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id 2637961572 for ; Wed, 10 Jul 2019 21:17:48 +0200 (CEST) Received: from pendragon.ideasonboard.com (softbank126163157105.bbtec.net [126.163.157.105]) by perceval.ideasonboard.com (Postfix) with ESMTPSA id D609C54B for ; Wed, 10 Jul 2019 21:17:46 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1562786267; bh=/G/wkHj72tFg4KLIlPYqXDUF7DJ8+ekYrwji7P8IrXg=; h=From:To:Subject:Date:In-Reply-To:References:From; b=L9vSdzzEN1w1QxQ7Zr/qxtNDGzFI5Q2Yw3T/khnpxbqTlRf6ctNj/04q8U4mNJn5A cjhDrcnNwpKva4WfOV0VrkjAnLr0hfPobdHFJcBS9UTn/SUcRIu1PI03Pq7PkX8NLD ASmA8xfxcddPve5Guw6+VqC6OApX2M60VbjMpB+4= From: Laurent Pinchart To: libcamera-devel@lists.libcamera.org Date: Wed, 10 Jul 2019 22:17:07 +0300 Message-Id: <20190710191708.13049-5-laurent.pinchart@ideasonboard.com> X-Mailer: git-send-email 2.21.0 In-Reply-To: <20190710191708.13049-1-laurent.pinchart@ideasonboard.com> References: <20190710191708.13049-1-laurent.pinchart@ideasonboard.com> MIME-Version: 1.0 Subject: [libcamera-devel] [PATCH 5/6] test: Add Message test case X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.23 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Wed, 10 Jul 2019 19:17:48 -0000 The Message class test creates a receiver inheriting from Object, moves it to a different thread, sends a message to the receiver and verifies that the message is delivered in the correct thread. Signed-off-by: Laurent Pinchart Reviewed-by: Niklas Söderlund --- test/meson.build | 1 + test/message.cpp | 88 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 test/message.cpp diff --git a/test/meson.build b/test/meson.build index bd0e0d98f0e7..1f87319aeb65 100644 --- a/test/meson.build +++ b/test/meson.build @@ -21,6 +21,7 @@ public_tests = [ internal_tests = [ ['camera-sensor', 'camera-sensor.cpp'], + ['message', 'message.cpp'], ['threads', 'threads.cpp'], ] diff --git a/test/message.cpp b/test/message.cpp new file mode 100644 index 000000000000..de98da3e8754 --- /dev/null +++ b/test/message.cpp @@ -0,0 +1,88 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2019, Google Inc. + * + * message.cpp - Messages test + */ + +#include +#include +#include + +#include "message.h" +#include "thread.h" +#include "test.h" +#include "utils.h" + +using namespace std; +using namespace libcamera; + +class MessageReceiver : public Object +{ +public: + enum Status { + NoMessage, + InvalidThread, + MessageReceived, + }; + + MessageReceiver() + : status_(NoMessage) + { + } + + Status status() const { return status_; } + void reset() { status_ = NoMessage; } + +protected: + void message(Message *msg) + { + if (thread() != Thread::current()) + status_ = InvalidThread; + else + status_ = MessageReceived; + } + +private: + Status status_; +}; + +class MessageTest : public Test +{ +protected: + int run() + { + MessageReceiver receiver; + receiver.moveToThread(&thread_); + + thread_.start(); + + receiver.postMessage(utils::make_unique(Message::None)); + + this_thread::sleep_for(chrono::milliseconds(100)); + + switch (receiver.status()) { + case MessageReceiver::NoMessage: + cout << "No message received" << endl; + return TestFail; + case MessageReceiver::InvalidThread: + cout << "Message received in incorrect thread" << endl; + return TestFail; + default: + break; + } + + return TestPass; + } + + void cleanup() + { + thread_.exit(0); + thread_.wait(); + } + +private: + Thread thread_; +}; + +TEST_REGISTER(MessageTest) From patchwork Wed Jul 10 19:17:08 2019 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Laurent Pinchart X-Patchwork-Id: 1649 Return-Path: Received: from perceval.ideasonboard.com (perceval.ideasonboard.com [213.167.242.64]) by lancelot.ideasonboard.com (Postfix) with ESMTPS id DBF9C6156E for ; Wed, 10 Jul 2019 21:17:49 +0200 (CEST) Received: from pendragon.ideasonboard.com (softbank126163157105.bbtec.net [126.163.157.105]) by perceval.ideasonboard.com (Postfix) with ESMTPSA id 8A4BC54B for ; Wed, 10 Jul 2019 21:17:48 +0200 (CEST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=ideasonboard.com; s=mail; t=1562786269; bh=CK8a7gmWvZY09dYumDGB1As4oCZj7stHZcbwYbdrBgA=; h=From:To:Subject:Date:In-Reply-To:References:From; b=adpfBEYRKtP/Yf94fR7yVkTetKSnWV0MkitRO8dAyxK0e8kI3xxAbi3AMKNCl3g/o 7ySUkl37ybhd/EpjYFXx6iXBMP7VAW32Qmgn4zANx/KyDKUcl6W1TWfK4zKEL/vCE1 I6ZOimE7G+YEOF3n1ThfhOFnjxRAc/2mvMGFFHJk= From: Laurent Pinchart To: libcamera-devel@lists.libcamera.org Date: Wed, 10 Jul 2019 22:17:08 +0300 Message-Id: <20190710191708.13049-6-laurent.pinchart@ideasonboard.com> X-Mailer: git-send-email 2.21.0 In-Reply-To: <20190710191708.13049-1-laurent.pinchart@ideasonboard.com> References: <20190710191708.13049-1-laurent.pinchart@ideasonboard.com> MIME-Version: 1.0 Subject: [libcamera-devel] [PATCH 6/6] test: Add test case for signal delivery across threads X-BeenThere: libcamera-devel@lists.libcamera.org X-Mailman-Version: 2.1.23 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Wed, 10 Jul 2019 19:17:50 -0000 The test case creates a receiver inheriting from Object, connects a signal to one of its slot, moves the receiver to a different thread, emits the signal and verifies that it gets delivered in the correct thread with the expected value. Signed-off-by: Laurent Pinchart Reviewed-by: Niklas Söderlund --- test/meson.build | 1 + test/signal-threads.cpp | 125 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 test/signal-threads.cpp diff --git a/test/meson.build b/test/meson.build index 1f87319aeb65..60ce9601cc55 100644 --- a/test/meson.build +++ b/test/meson.build @@ -22,6 +22,7 @@ public_tests = [ internal_tests = [ ['camera-sensor', 'camera-sensor.cpp'], ['message', 'message.cpp'], + ['signal-threads', 'signal-threads.cpp'], ['threads', 'threads.cpp'], ] diff --git a/test/signal-threads.cpp b/test/signal-threads.cpp new file mode 100644 index 000000000000..c21f32ae0c20 --- /dev/null +++ b/test/signal-threads.cpp @@ -0,0 +1,125 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2019, Google Inc. + * + * signal-threads.cpp - Cross-thread signal delivery test + */ + +#include +#include +#include + +#include "message.h" +#include "thread.h" +#include "test.h" +#include "utils.h" + +using namespace std; +using namespace libcamera; + +class SignalReceiver : public Object +{ +public: + enum Status { + NoSignal, + InvalidThread, + SignalReceived, + }; + + SignalReceiver() + : status_(NoSignal) + { + } + + Status status() const { return status_; } + int value() const { return value_; } + void reset() + { + status_ = NoSignal; + value_ = 0; + } + + void slot(int value) + { + if (Thread::current() != thread()) + status_ = InvalidThread; + else + status_ = SignalReceived; + + value_ = value; + } + +private: + Status status_; + int value_; +}; + +class SignalThreadsTest : public Test +{ +protected: + int run() + { + SignalReceiver receiver; + signal_.connect(&receiver, &SignalReceiver::slot); + + /* Test that a signal is received in the main thread. */ + signal_.emit(42); + + switch (receiver.status()) { + case SignalReceiver::NoSignal: + cout << "No signal received for direct connection" << endl; + return TestFail; + case SignalReceiver::InvalidThread: + cout << "Signal received in incorrect thread " + "for direct connection" << endl; + return TestFail; + default: + break; + } + + /* + * Move the object to a thread and verify that the signal is + * correctly delivered, with the correct data. + */ + receiver.reset(); + receiver.moveToThread(&thread_); + + thread_.start(); + + signal_.emit(42); + + this_thread::sleep_for(chrono::milliseconds(100)); + + switch (receiver.status()) { + case SignalReceiver::NoSignal: + cout << "No signal received for message connection" << endl; + return TestFail; + case SignalReceiver::InvalidThread: + cout << "Signal received in incorrect thread " + "for message connection" << endl; + return TestFail; + default: + break; + } + + if (receiver.value() != 42) { + cout << "Signal received with incorrect value" << endl; + return TestFail; + } + + return TestPass; + } + + void cleanup() + { + thread_.exit(0); + thread_.wait(); + } + +private: + Thread thread_; + + Signal signal_; +}; + +TEST_REGISTER(SignalThreadsTest)