/* * Copyright © 2015 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . * * Authors: * Ted Gould */ #pragma once #include #include #include #include namespace GLib { class ContextThread { std::thread _thread; std::shared_ptr _context; std::shared_ptr _loop; std::shared_ptr _cancel; std::function afterLoop_; std::shared_ptr afterFlag_; public: ContextThread(const std::function& beforeLoop = [] {}, const std::function& afterLoop = [] {}); ~ContextThread(); void quit(); bool isCancelled(); std::shared_ptr getCancellable(); guint executeOnThread(std::function work); template auto executeOnThread(std::function work) -> T { if (std::this_thread::get_id() == _thread.get_id()) { /* Don't block if we're on the same thread */ return work(); } std::promise promise; std::function magicFunc = [&promise, &work]() { try { promise.set_value(work()); } catch (...) { promise.set_exception(std::current_exception()); } }; executeOnThread(magicFunc); auto future = promise.get_future(); future.wait(); return future.get(); } guint timeout(const std::chrono::milliseconds& length, std::function work); template guint timeout(const std::chrono::duration& length, std::function work) { return timeout(std::chrono::duration_cast(length), work); } guint timeoutSeconds(const std::chrono::seconds& length, std::function work); template guint timeoutSeconds(const std::chrono::duration& length, std::function work) { return timeoutSeconds(std::chrono::duration_cast(length), work); } void removeSource(guint sourceid); private: guint simpleSource(std::function srcBuilder, std::function work); }; }