libuv線程通信


1、說明

用於多線程之間傳遞參數

2、API

2.1、uv_async_init

int uv_async_init(uv_loop_t* loop, uv_async_t* async, uv_async_cb async_cb);

初始化句柄(uv_async_t 類型),回調函數 async_cb 可以為NULL

返回0表示成功,<0 表示錯誤碼

2.2、uv_async_send

int uv_async_send(uv_async_t* async);

喚醒時間循環,執行 async 的回調函數(uv_async_init 初始化指定的回調)

async 將被傳遞給回調函數

返回0表示成功,<0 表示錯誤碼

在任何線程中調用此方法都是安全的,回調函數將會在 uv_async_init 指定的 loop 線程中執行

2.3、uv_close

void uv_close(uv_handle_t* handle, uv_close_cb close_cb)

uv_async_init 對應,調用之后執行回調 close_cb

handle 會被立即釋放,但是 close_cb 會在事件循環到來之時執行,用於釋放句柄相關的其他資源

3、代碼示例

#include <iostream>
#include <uv.h>
#include <stdio.h>
#include <unistd.h>

uv_loop_t *loop;
uv_async_t async;

double percentage;

void print(uv_async_t *handle)
{
    printf("thread id: %ld, value is %ld\n", uv_thread_self(), (long)handle->data);
}

void run(uv_work_t *req)
{
    long count = (long)req->data;
    for (int index = 0; index < count; index++)
    {
        printf("run thread id: %ld, index: %d\n", uv_thread_self(), index);
        async.data = (void *)(long)index;
        uv_async_send(&async);
        sleep(1);
    }
}

void after(uv_work_t *req, int status)
{
    printf("done, thread id: %ld\n", uv_thread_self());
    uv_close((uv_handle_t *)&async, NULL);
}

int main()
{
    printf("main thread id: %ld\n", uv_thread_self());
    loop = uv_default_loop();

    uv_work_t req;
    int size = 5;
    req.data = (void *)(long)size;

    uv_async_init(loop, &async, print);
    uv_queue_work(loop, &req, run, after);

    return uv_run(loop, UV_RUN_DEFAULT);
}

示例中,print() 函數將會在 loop 所在的線程中執行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM