I am writing a node.js inspired C++ library for asynchronous function calls.
How efficient and stable does my code look?
If you want, you can see some WIP code and demonstration code here. (net.hpp is for POSIX sockets and is far from done. It does not have any IO functions written)
/* ASYNC.HPP
* Defines some functions for calling other functions in the background
* This gives the ability to create callback based functions easily,
* similar to node.js (But I hate javascript so I wrote this library for c++)
*/
#ifndef ASYNC_H
#define ASYNC_H
#include <thread>
#include <vector>
std::vector<std::thread> asyncCalls; // Don't have to deal with threads leaving scope since this vector is global
#define asyncCall asyncCalls.emplace_back // Whenever someone calls asyncCall this constructs a new std::thread which calls their function
void finishAsync(){ //Call to block until all running asyncronous functions return
while(!asyncCalls.empty()){ //Loop until the vector is empty
asyncCalls.back().join(); //Get the thread from the back and join it to block
//^ I feel like this line might throw an exception, but in my testing it hasn't thrown anything.
asyncCalls.pop_back(); //Pop it and get a new one
}
} // Infinite running threads will block forever
#ifdef _GLIBCXX_CHRONO //Include <chrono> before this header for this function
void sleep(uint32_t millis){ //I just realized while adding comments that I could do this with a define. Oh well
std::this_thread::sleep_for(std::chrono::milliseconds(millis));
}
#endif // End chrono function
#endif //End header guard
select()
,pselect()
,poll()
,libEvent()
. On the language side if you still want to do it with threads you need to learn about hire level featuresstd::future
,std::promise
andstd::async
\$\endgroup\$