Skip to content

Commit

Permalink
new: luv_cleanup to handle cleanup of non-gc resources
Browse files Browse the repository at this point in the history
This adds a solution to the problem of cleaning up
luv resources when using an external uv_loop_t in
cases such as neovim.

This function is necessary for external loops to
not leak memory when luv is no longer in use.
  • Loading branch information
truemedian committed Jan 29, 2025
1 parent 1b29585 commit f999dad
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/luv.c
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,11 @@ LUALIB_API void luv_set_loop(lua_State* L, uv_loop_t* loop) {
ctx->mode = -1;
}

// Clean up luv resources when using an external loop, after the loop has stopped.
LUALIB_API void luv_cleanup(void) {
luv_work_cleanup();
}

// Set an external event callback routine, before luaopen_luv
LUALIB_API void luv_set_callback(lua_State* L, luv_CFpcall pcall) {
luv_ctx_t* ctx = luv_context(L);
Expand Down Expand Up @@ -855,7 +860,7 @@ static int loop_gc(lua_State *L) {
/* do cleanup in main thread */
lua_getglobal(L, "_THREAD");
if (lua_isnil(L, -1))
luv_work_cleanup();
luv_cleanup();
lua_pop(L, 1);
return 0;
}
Expand Down
7 changes: 7 additions & 0 deletions src/luv.h
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,13 @@ LUALIB_API uv_loop_t* luv_loop(lua_State* L);
*/
LUALIB_API void luv_set_loop(lua_State* L, uv_loop_t* loop);

/* Free all non-garbaged-collected resources allocated by luv. This function
must be called when using an external uv_loop_t, it is called during garbage
collection of the Lua userdata for the uv_loop_t otherwise. This must only
be called after all lua_States using luv have stopped their uv_loop_t.
*/
LUALIB_API void luv_cleanup(void);

/* Set or clear an external c routine for luv event callback
When using a custom/external function, this must be called before luaopen_luv
(otherwise luv will use the default callback function: luv_cfpcall)
Expand Down

0 comments on commit f999dad

Please sign in to comment.