79 lines
1020 B
C++
79 lines
1020 B
C++
// TJP COPYRIGHT HEADER
|
|
|
|
#pragma once
|
|
|
|
#include "Runnable.h"
|
|
|
|
#include <tjp/core/ptr/Ptr.hpp>
|
|
#include <tjp/core/future/Future.hpp>
|
|
#include <tjp/core/containers/Optional.hpp>
|
|
|
|
#include <tjp/core/future/Future.h>
|
|
|
|
namespace tjp::core {
|
|
|
|
struct Endable;
|
|
|
|
struct Runnable : StrongThis<Runnable>
|
|
{
|
|
using End = Function<void(Runnable &)>;
|
|
|
|
Runnable(End &&end) :
|
|
end_(std::move(end))
|
|
{}
|
|
|
|
Function<void(Runnable &)> end_;
|
|
|
|
bool end = false;
|
|
Promise<int> ended;
|
|
|
|
Endable getEndable();
|
|
} ;
|
|
|
|
struct Endable
|
|
{
|
|
StrongPtr<Runnable> runnable;
|
|
bool endOnDestruct_ = false;
|
|
|
|
~Endable()
|
|
{
|
|
if (endOnDestruct_)
|
|
{
|
|
end();
|
|
get_future().wait();
|
|
}
|
|
}
|
|
|
|
void endOnDestruct()
|
|
{
|
|
endOnDestruct_ = true;
|
|
}
|
|
|
|
void end()
|
|
{
|
|
runnable->end = true;
|
|
|
|
if (runnable->end_)
|
|
{
|
|
runnable->end_(*runnable);
|
|
runnable->end_ = {};
|
|
}
|
|
}
|
|
|
|
Future<int> get_future()
|
|
{
|
|
return runnable->ended.get_future();
|
|
}
|
|
} ;
|
|
|
|
inline
|
|
Endable Runnable::getEndable()
|
|
{
|
|
return Endable {
|
|
strong_this(this)
|
|
};
|
|
}
|
|
|
|
|
|
} // namespace
|