Async Framework is c++ runtime with timers, poll notifiers, sockets, coroutines, etc.
Is a software framework that allows developers to build applications using asynchronous programming, which runs operations concurrently without blocking the main thread.
See documentation and examples for details.
Timer example:
#include <iostream>
#include <chrono>
#include <core/Thread.h>
#include <MainThread.h>
#include <Timer.h>
int main(int argc, char *argv[]) {
int cnt = 0;
std::cout << std::chrono::system_clock::now() << " timer1 timeout" << std::endl;
if (++cnt == 10) AsyncFw::MainThread::exit(0);
});
timer2.
timeout([]() { std::cout << std::chrono::system_clock::now() <<
" timer2 timeout" << std::endl; });
std::cout << "Start Applicaiton" << std::endl;
int ret = AsyncFw::MainThread::exec();
return ret;
}
The Timer class.
Definition Timer.h:15
void start(int, bool=false)
Starts or restarts a timer with the specified timeout. If the timer is already running,...
Definition Timer.cpp:29
FunctionConnectorProtected< Timer >::Connector<> timeout
The Timer::timeout connector.
Definition Timer.h:31
PollNotifier example (Unix only):
#include <iostream>
#include <core/Thread.h>
#include <MainThread.h>
#include <PollNotifier.h>
int main(int argc, char *argv[]) {
if (isatty(STDIN_FILENO)) {
notifier.notify([¬ifier](AsyncFw::AbstractThread::PollEvents e) {
char buf[128];
int r = read(STDIN_FILENO, buf, sizeof(buf) - 1);
buf[r] = 0;
if (r == 2 && buf[0] == 'q') AsyncFw::MainThread::exit();
std::cout << "stdin: " << buf;
});
} else {
std::cout << "stdin is not connected to the terminal";
return -1;
}
std::cout << "Start Applicaiton" << std::endl;
int ret = AsyncFw::MainThread::exec();
return ret;
}
The PollNotifier class Example:
Definition PollNotifier.h:15
Log example:
#include <Log.h>
#include <MainThread.h>
int main(int argc, char *argv[]) {
logTrace() << "Trace";
logDebug() << "Debug";
logInfo() << "Info";
logNotice() << "Notice";
logWarning() << "Warning";
logError() << "Error";
logAlert() << "logAlert";
logEmergency() << "Emergency";
return 0;
}
The Log class.
Definition Log.h:71
Executing method in another thread example:
#include <core/Thread.h>
#include <MainThread.h>
#include <Log.h>
int main(int argc, char *argv[]) {
thread1.start();
thread2.start();
logDebug() <<
"Main id:" << _mainThread->
id();
logDebug() << "T1 id:" << thread1.id();
logDebug() << "T2 id:" << thread2.id();
thread1.invokeMethod([&thread2, _mainThread]() {
logInfo() <<
"run in thread" << ct->
name() << ct->
id();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
thread2.invokeMethod([_mainThread]() {
logInfo() <<
"run in thread" << ct->
name() << ct->
id();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
logInfo() <<
"run in thread" << ct->
name() << ct->
id();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
logInfo() << "exit application";
AsyncFw::MainThread::exit(0);
});
});
});
logNotice() << "Start Applicaiton";
int ret = AsyncFw::MainThread::exec();
logNotice() << "End Applicaiton";
return ret;
}
The AbstractThread class provides the base functionality for thread management.
Definition AbstractThread.h:46
std::string name() const
Returns name of managed thread.
Definition AbstractThread.cpp:671
std::thread::id id() const
Returns unique identifier of managed thread.
Definition AbstractThread.cpp:669
std::enable_if< std::is_void< typenamestd::invoke_result< M >::type >::value, bool >::type invokeMethod(M method, bool sync=false) const
Runs a method in a managed thread.
Definition AbstractThread.h:74
static AbstractThread * currentThread()
Returns a pointer to the AsyncFw::AbstractThread that manages the currently executing thread.
Definition AbstractThread.cpp:295
AsyncFw::Thread thread with sockets.
Definition Thread.h:16
FunctionConnector example:
#include <core/Thread.h>
#include <core/FunctionConnector.h>
#include <Timer.h>
#include <MainThread.h>
#include <Log.h>
class Sender {
public:
Sender() {
timer.timeout([this]() {
logInfo() << cnt <<
"send from thread:" << ct->
name() << ct->
id();
connector(cnt++);
if (cnt == 3) AsyncFw::MainThread::exit(0);
});
timer.start(1000);
}
mutable AsyncFw::FunctionConnectorProtected<Sender>::Connector<int> connector;
private:
int cnt = 0;
AsyncFw::Timer timer;
};
class Receiver {
public:
Receiver(const std::string &name, const Sender &sender) {
sender.connector([name_ = name](int val) {
logInfo() << name_ <<
"received" << val <<
"run in thread" << ct->
name() << ct->
id();
});
}
};
int main(int argc, char *argv[]) {
Sender *sender;
thread.start();
thread.invokeMethod(
[&sender]() {
sender = new Sender;
},
true);
Receiver receiver1("R1", *sender);
Receiver receiver2("R2", *sender);
logNotice() << "Start Applicaiton";
int ret = AsyncFw::MainThread::exec();
logNotice() << "End Applicaiton";
delete sender;
return ret;
}
ThreadPool example:
#include <core/Thread.h>
#include <ThreadPool.h>
#include <MainThread.h>
#include <Log.h>
int main(int argc, char *argv[]) {
AsyncFw::ThreadPool *threadPool = AsyncFw::Instance<AsyncFw::ThreadPool>::create(
"ExampeThreadPool");
AsyncFw::ThreadPool::sync(_t, []() {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
logInfo() <<
"sync run in thread" << ct->
name() << ct->
id();
});
AsyncFw::ThreadPool::async([]() {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
logInfo() <<
"async run in thread" << ct->
name() << ct->
id();
});
AsyncFw::ThreadPool::async(
[]() {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
logInfo() <<
"async run in thread" << ct->
name() << ct->
id();
},
[]() {
logNotice() <<
"result without value, run in thread" << ct->
name() << ct->
id();
});
AsyncFw::ThreadPool::async(
[]() {
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
logInfo() <<
"async run in thread" << ct->
name() << ct->
id();
return 1;
},
[](int r) {
logNotice() <<
"result:" << r <<
"run in thread" << ct->
name() << ct->
id();
AsyncFw::MainThread::exit(0);
});
logNotice() << "Start Applicaiton";
int ret = AsyncFw::MainThread::exec();
logNotice() << "End Applicaiton" << ret;
return ret;
}
Управляет набором многократно используемых рабочих потоков для параллельного выполнения задач,...
Definition ThreadPool.h:60
Coroutine example:
#include <thread>
#include <MainThread.h>
#include <ThreadPool.h>
#include <Coroutine.h>
#include <Log.h>
AsyncFw::ThreadPool::async(
[h]() {
logInfo() <<
"task: run in thread" << ct->
name() << ct->
id();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
},
[h]() {
logInfo() <<
"task: resume in thread" << ct->
name() << ct->
id();
h.resume();
});
});
co_await await;
logNotice() <<
"task: resumed in thread" << ct->
name() << ct->
id();
}
int main(int argc, char *argv[]) {
AsyncFw::Instance<AsyncFw::ThreadPool>::create("CoroutineExamplePool");
task();
AsyncFw::ThreadPool::async(
[h]() {
logInfo() <<
"coro_task: run in thread" << ct->
name() << ct->
id();
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
},
[h]() {
logInfo() <<
"coro_task: resume in thread" << ct->
name() << ct->
id();
h.resume();
});
});
co_await await;
logNotice() <<
"coro_task: resumed in thread" << ct->
name() << ct->
id();
AsyncFw::MainThread::exit(0);
});
coro_task();
logNotice() << "Start Applicaiton";
int ret = AsyncFw::MainThread::exec();
logNotice() << "End Applicaiton";
return ret;
}
The CoroutineAwait struct.
Definition Coroutine.h:51
The CoroutineTask struct.
Definition Coroutine.h:18
Tls socket example:
#include <core/Thread.h>
#include <MainThread.h>
#include <core/TlsSocket.h>
#include <core/TlsContext.h>
#include <AddressInfo.h>
#include <Log.h>
public:
void stateEvent() {
logDebug() << "State event:" << static_cast<int>(state_);
if (state_ == Active) {
logDebug() << "Send request";
write("GET /a-ucontrol/AsyncFw HTTP/1.1\r\nHost:github.com\r\nConnection:close\r\n\r\n");
} else if (error() >= Closed) {
if (error() != Closed) logError() << errorString();
else {
logNotice() << "Received:" << da;
logDebug() << da.view(0, 512) << "...";
}
AsyncFw::MainThread::exit(0);
}
}
void readEvent() {
AsyncFw::DataArray _da = read();
logTrace() << "Read event:" << _da.size() << std::endl << _da.view(0, 256);
da += _da;
}
private:
AsyncFw::DataArray da;
};
int main(int argc, char *argv[]) {
if (!context.setDefaultVerifyPaths()) {
logError("Can't set default verify paths");
return -1;
}
context.setVerifyName("github.com");
TcpSocket socket;
socket.setContext(context);
addressInfo.resolve("github.com");
addressInfo.
completed([&socket](
int r,
const std::vector<std::string> &list) {
if (r == 0 && !list.empty()) {
for (const std::string _s : list) logNotice() << _s;
socket.connect(list[0], 443);
}
});
logNotice() << "Start Applicaiton";
int ret = AsyncFw::MainThread::exec();
logNotice() << "End Applicaiton";
return ret;
}
The AbstractTlsSocket class provides the base functionality for TLS encrypted socket.
Definition AbstractTlsSocket.h:17
The AddressInfo class.
Definition AddressInfo.h:29
FunctionConnectorProtected< AddressInfo >::Connector< int, const std::vector< std::string > & > completed
The AddressInfo::completed connector.
Definition AddressInfo.h:42
The TlsContext class provides functionality for managing TLS certificates.
Definition TlsContext.h:24
Container task example:
#include <queue>
#include <MainThread.h>
#include <Timer.h>
#include <Task.h>
#include <core/LogStream.h>
int main(int argc, char *argv[]) {
std::queue<std::shared_ptr<AsyncFw::AbstractTask>> tasks;
for (int i = 0; i != 10; ++i) {
std::shared_ptr<AsyncFw::AbstractTask> task = std::shared_ptr<AsyncFw::AbstractTask>(
new AsyncFw::Task([](std::any *data) { logInfo() <<
"task:" << std::any_cast<int>(*data); }, &thread));
task->setData(i);
tasks.push(task);
}
if (tasks.empty()) {
AsyncFw::MainThread::exit(0);
return;
}
lsInfoGreen() << tasks.front()->running();
(*tasks.front())();
lsInfoGreen() << tasks.front()->running();
tasks.pop();
});
logNotice() << "Start Applicaiton";
int ret = AsyncFw::MainThread::exec();
logNotice() << "End Applicaiton";
return ret;
}
void start()
Create a managed thread and run exec().
Definition AbstractThread.cpp:635
The Task class.
Definition Task.h:25
Listen socket example:
#include <MainThread.h>
#include <core/TlsSocket.h>
#include <Log.h>
public:
static TcpSocket *create() { return new TcpSocket; }
void stateEvent() { logDebug() << "State event:" << static_cast<int>(state_); }
void readEvent() { received(read()); }
AsyncFw::FunctionConnectorProtected<TcpSocket>::Connector<const AsyncFw::DataArray &> received;
};
int main(int argc, char *argv[]) {
ls.setIncomingConnection([](int fd, const std::string &address) {
TcpSocket *socket = TcpSocket::create();
socket->setDescriptor(fd);
logNotice() << "received:" << data;
socket->write("Answer\n");
AsyncFw::MainThread::exit(0);
});
logInfo() << "Incoming:" << fd << address;
return true;
});
ls.listen("0.0.0.0", 18080);
logNotice() << "Start Applicaiton";
int ret = AsyncFw::MainThread::exec();
logNotice() << "End Applicaiton";
return ret;
}
The DataArray class.
Definition DataArray.h:20
The ListenSocket class.
Definition ListenSocket.h:16
SystemProcess example (Unix only):
#include <MainThread.h>
#include <linux/SystemProcess.h>
#include <Timer.h>
#include <core/LogStream.h>
int main(int argc, char *argv[]) {
process.
output([](
const std::string &str,
bool err) {
if (!err) logInfo() << "OUT:" << '\n' + str;
else { logError() << "ERR:" << '\n' + str; }
});
if (_s == AsyncFw::SystemProcess::Running) return;
AsyncFw::MainThread::exit(0);
});
process.start("/bin/bash");
logNotice() << "Start Applicaiton";
int ret = AsyncFw::MainThread::exec();
return ret;
}
The SystemProcess class.
Definition SystemProcess.h:16
FunctionConnectorProtected< SystemProcess >::Connector< State > stateChanged
The FunctionConnector for SystemProcess stateChanged.
Definition SystemProcess.h:30
FunctionConnectorProtected< SystemProcess >::Connector< const std::string &, bool > output
The FunctionConnector for SystemProcess output.
Definition SystemProcess.h:32
static void single(int ms, T function)
Starts a single shot timer with the specified timeout.
Definition Timer.h:19