Files
SnowLuma/.pnpm-store/v11/files/9f/08d0a190b5e78b2e9bcfa27aa9e4487d6ba6ca20c146ff754ce4e79583cd2e819b6cd2a1ddc339ba3a3d0cb6009234db063f0868469dc6ed7c1c4de009184a
TanTan 2a69b23b47
Dev Build / cleanup (push) Waiting to run
Dev Build / typecheck (push) Waiting to run
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

86 lines
2.2 KiB
Plaintext

#ifndef NODE_SQLITE3_SRC_ASYNC_H
#define NODE_SQLITE3_SRC_ASYNC_H
#include <napi.h>
#include <uv.h>
#include "threading.h"
// Generic uv_async handler.
template <class Item, class Parent> class Async {
typedef void (*Callback)(Parent* parent, Item* item);
protected:
uv_async_t watcher;
NODE_SQLITE3_MUTEX_t
std::vector<Item*> data;
Callback callback;
public:
Parent* parent;
public:
Async(Parent* parent_, Callback cb_)
: callback(cb_), parent(parent_) {
watcher.data = this;
NODE_SQLITE3_MUTEX_INIT
uv_loop_t *loop;
napi_get_uv_event_loop(parent_->Env(), &loop);
uv_async_init(loop, &watcher, reinterpret_cast<uv_async_cb>(listener));
}
static void listener(uv_async_t* handle) {
auto* async = static_cast<Async*>(handle->data);
std::vector<Item*> rows;
NODE_SQLITE3_MUTEX_LOCK(&async->mutex)
rows.swap(async->data);
NODE_SQLITE3_MUTEX_UNLOCK(&async->mutex)
for(auto row : rows)
async->callback(async->parent, row);
}
static void close(uv_handle_t* handle) {
assert(handle != NULL);
assert(handle->data != NULL);
auto* async = static_cast<Async*>(handle->data);
delete async;
}
void finish() {
// Need to call the listener again to ensure all items have been
// processed. Is this a bug in uv_async? Feels like uv_close
// should handle that.
listener(&watcher);
uv_close((uv_handle_t*)&watcher, close);
}
// Delivers whatever is already queued, now, on the calling thread —
// which must be the JS thread, since the callback enters JS. Used by
// Database::_flushProfile so a caller that has just awaited a query
// can read its span instead of waiting for the loop turn on which the
// uv_async callback happens to run.
void flush() {
listener(&watcher);
}
void add(Item* item) {
NODE_SQLITE3_MUTEX_LOCK(&mutex);
data.emplace_back(item);
NODE_SQLITE3_MUTEX_UNLOCK(&mutex)
}
void send() {
uv_async_send(&watcher);
}
void send(Item* item) {
add(item);
send();
}
~Async() {
NODE_SQLITE3_MUTEX_DESTROY
}
};
#endif