Skip to content

How to Share libuv Event Loop Between Luvi and a Custom C Dynamic Library #303

@t59688

Description

@t59688

Hi Luvi

I'm building a custom C dynamic library that I want to integrate with Luvi. My library uses libuv for asynchronous operations, and I want to ensure that it shares the same libuv event loop as Luvi to avoid conflicts and resource duplication.

Here's a simplified version of my C code:

#include <uv.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

static uv_async_t *luvi_async = NULL;
static char *message = NULL;

typedef struct
{
    char *data;
} async_data_t;

void *thread_func(void *arg)
{
    // Wait for 1 second
    sleep(1);

    // Set the message
    if (message)
    {
        free(message);
    }
    message = strdup("Hello from thread!");

    // Send an async event
    if (luvi_async)
    {
        printf("Sending async event\n");
        uv_async_send(luvi_async);
    }

    return NULL;
}

void xx_init(void *async)
{
    luvi_async = (uv_async_t *)async; // Store the uv_async_t*
}

void xx_do_something()
{
    pthread_t tid;

    // Create a thread that sends an async event after 1 second
    if (pthread_create(&tid, NULL, thread_func, NULL) != 0)
    {
        fprintf(stderr, "Failed to create thread\n");
        return;
    }

    // Detach the thread
    pthread_detach(tid);
}

// Function to get the message, callable from Lua
const char *xx_get_message()
{
    return message ? message : "";
}

and lua code

local uv = require('uv')
local ffi = require('ffi')

ffi.cdef [[
    void xx_init(void *async);
    void xx_do_something();
    const char *xx_get_message();
]]
local lccu = ffi.load('/cmake-build/lccu/liblccu.so')

local global_async = uv.new_async(function()
    print("Async callback triggered!")
end)

lccu.xx_init(global_async) -- 传递 uv_async_t*
lccu.xx_do_something()

uv.run()

My main question is: How can I ensure that my dynamic library and Luvi link to the same libuv library and share the same event loop instance?

I'm looking for guidance on:

  • The correct way to compile and link my dynamic library with Luvi.
  • Any necessary runtime configurations to ensure that both use the same libuv instance.
  • Best practices for passing the uv_async_t handle from Luvi to my C library.
  • I'm compiling Luvi from source.

Any help or pointers would be greatly appreciated!

Thank you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions