help icon indicating copy to clipboard operation
help copied to clipboard

Is there a way to use blocking mode with uv_tcp_read ?

Open BillHoo opened this issue 7 years ago • 5 comments

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 avatar Dec 24 '18 08:12 BillHoo

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

BillHoo avatar Jan 04 '19 01:01 BillHoo

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.

jamadden avatar Jan 04 '19 01:01 jamadden

@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

BillHoo avatar Jan 04 '19 01:01 BillHoo

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

jamadden avatar Jan 04 '19 02:01 jamadden

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?

BillHoo avatar Jan 04 '19 02:01 BillHoo