libuv / help

Need help with libuv? Post your question here.
28 stars 7 forks source link

Is there a way to use blocking mode with uv_tcp_read ? #77

Open BillHoo opened 5 years ago

BillHoo commented 5 years ago

Hi libuv team,

I'm using libuv for TCP connection for a long time, its easy and reliable, but now I'm encounter a challenge, and need your help:

libuv's default behaviour of TCP connections is non-blocking mode, which means I must call uv_run in a loop in order to trigger the uv_process_tcp_read_req:

while (_keep_main_loop) {
    {
        std::lock_guard<std::recursive_mutex> lg(_main_loop_mtx);
        if (_main_loop) {
            uv_run(_main_loop, UV_RUN_NOWAIT);
        }
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(1));
}

The problem is that sleep(1ms) can be very tricky on some mobile devices (even Mac OSX in battery mode), when mobile system get into deep sleep mode, it will stop CPU's work, so the sleep(1ms) will delayed to minutes even hours, that means I can not trigger uv_run on time, so can not receive TCP data on time.

My question is: Is there's a way for me to change libuv's TCP module to blocking mode? Like blocking on select ?

If uv_run blocked on some IO API when there's no TCP data, I can avoid call sleep(1ms), and AFAIK when new data is arrived, the system will awake the blocking IO immediately even it is in deep sleep mode, so my data will be received on time.

Thanks in advance, Bill

BillHoo commented 5 years ago

Any ideas guys? i'm stucked on it, thanks

jamadden commented 5 years ago

Have you considered UV_RUN_ONCE (or UV_RUN_DEFAULT) instead of UV_RUN_NOWAIT? Whatever changes the value of _keep_main_loop would then want to trigger an async watcher to wake the loop up.

BillHoo commented 5 years ago

@jamadden sorry i'm not get it, I've tried UV_RUN_ONCE before but with no lucky (i doubt that i'm doing something wrong with this flag), could you please show me a piece of demo code? Thanks

jamadden commented 5 years ago

Sorry, no, I really don't have that kind of time right now.

BillHoo commented 5 years ago

no problem, i'll try it again, or is there any documents can lead me to a right way of using UV_RUN_ONCE in the main loop?