U
U
unclechu2014-07-25 02:22:15
C++ / C#
unclechu, 2014-07-25 02:22:15

How to sync libuv code?

There is just an example (below). The problem is that I need to wait for the completion of the code in after inside the process , how can I implement this correctly? Not while-loop in the end-same-ends to do?

uv_work_t *baton;

void work(uv_work_t* task) {}

void after(uv_work_t* task, int status) {
    printf("after\n");
    delete task;
}

int process()
{
    baton = new uv_work_t();
    uv_queue_work(uv_default_loop(), baton, work, after);
    printf("before\n");
    return 0;
}

PS The process itself is executed in a separate thread via pthread.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2014-07-25
@unclechu

Start a semaphore (uv_sem_*) that wait in process and cock it in after. Something like that:

static uv_sem_t sem;
uv_work_t *baton;

void work(uv_work_t* task) {}

void after(uv_work_t* task, int status) {
    printf("after\n");
    delete task;
    uv_sem_post(&sem);
}
int process()
{
    baton = new uv_work_t();
    if (uv_sem_init(&sem, 0) < 0) {
        perror("uv_sem_init");
        return -1;
    }
    uv_queue_work(uv_default_loop(), baton, work, after);
    printf("before\n");
    uv_sem_wait(&sem);
    uv_sem_destroy(&sem);
    return 0;
}

But the question arises: why use an asynchronous framework where you need synchronous execution of work? Isn't it possible to just call work from process?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question