Tweak Loop::get for "default" loops

This commit is contained in:
Alex Hultman
2019-03-02 04:36:06 +01:00
parent b1de3a5135
commit 35e6bad33b
2 changed files with 17 additions and 7 deletions
+12 -2
View File
@@ -76,20 +76,29 @@ private:
return this; return this;
} }
/* Todo: should take void ptr */
static Loop *create(bool defaultLoop) { static Loop *create(bool defaultLoop) {
return ((Loop *) us_create_loop(defaultLoop, wakeupCb, preCb, postCb, sizeof(LoopData)))->init(); return ((Loop *) us_create_loop(defaultLoop, wakeupCb, preCb, postCb, sizeof(LoopData)))->init();
} }
public: public:
/* Lazily initializes a per-thread loop and returns it. Will automatically free all initialized loops at exit. */ /* Lazily initializes a per-thread loop and returns it.
static Loop *get() { * Will automatically free all initialized loops at exit. */
static Loop *get(void *existingNativeLoop = nullptr) {
static thread_local Loop *lazyLoop; static thread_local Loop *lazyLoop;
if (!lazyLoop) { if (!lazyLoop) {
/* If we are given a native loop pointer we pass that to uSockets and let it deal with it */
if (existingNativeLoop) {
/* Todo: here we want to pass the pointer, not a boolean */
lazyLoop = create(true);
/* We cannot register automatic free here, must be manually done */
} else {
lazyLoop = create(false); lazyLoop = create(false);
std::atexit([]() { std::atexit([]() {
Loop::get()->free(); Loop::get()->free();
}); });
} }
}
return lazyLoop; return lazyLoop;
} }
@@ -98,6 +107,7 @@ public:
void free() { void free() {
LoopData *loopData = (LoopData *) us_loop_ext((us_loop *) this); LoopData *loopData = (LoopData *) us_loop_ext((us_loop *) this);
loopData->~LoopData(); loopData->~LoopData();
/* uSockets will track whether this loop is owned by us or a borrowed alien loop */
us_loop_free((us_loop *) this); us_loop_free((us_loop *) this);
} }