/*
* 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
*/
#include
#include
#include
namespace GLib
{
class ContextThread
{
std::thread _thread;
std::shared_ptr _context;
std::shared_ptr _loop;
std::shared_ptr _cancel;
public:
ContextThread (std::function beforeLoop = [] {}, std::function afterLoop = [] {});
~ContextThread ();
void quit ();
bool isCancelled ();
std::shared_ptr getCancellable ();
void 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] () -> void {
promise.set_value(work());
};
executeOnThread(magicFunc);
auto future = promise.get_future();
future.wait();
return future.get();
}
void timeout (const std::chrono::milliseconds& length, std::function work);
template void timeout (const std::chrono::duration& length,
std::function work)
{
return timeout(std::chrono::duration_cast(length), work);
}
void timeoutSeconds (const std::chrono::seconds& length, std::function work);
template void timeoutSeconds (const std::chrono::duration& length,
std::function work)
{
return timeoutSeconds(std::chrono::duration_cast(length), work);
}
private:
void simpleSource (std::function srcBuilder, std::function work);
};
}