4 ms·
that's the point. use nonblocking io and an event polling mechanism with a timeout to keep an eye on an exit flag- that's all you need to handle clean shutdowns
by a-dub 1y ago
that's the point. use nonblocking io and an event polling mechanism with a timeout to keep an eye on an exit flag- that's all you need to handle clean shutdowns.
i think on windows you can wait on both the sockets/file descriptors and condition variables with the same waitforxxxobject blocking mechanism. on linux you can do libevent, epoll, select or pthread_cond_timedwait. all of these have "release on event or after timeout" semantics. you can use eventfd to combine them.
i would not ever recommend relying on signals and writing custom cleanup handlers for them (!).
unless they're blocked waiting for an external event, most system calls tend to return in a reasonable amount of time. handle the external event blocking scenario (stuff that select waits for) and you're basically there. moreover, if you're looking to exit cleanly, you probably don't want to take your chances interrupting syscalls with signals (!) anyway.
> If you can't accept this, maybe don't play with threads, they are dangerous.
too late. when i first started playing with threads, linux didn't really support them.
- asveikau 1y ago> use nonblocking io and an event polling mechanism Not incompatible with what I said. > with a timeout to keep an eye on an exit flag This is the stupid part. You will burn CPU cycles waking up spuriously for timeouts with no work to do. Setting the flag won't wake up the event loop until the timeout hits, adding pointless delay. You want to make signalling an exit to actually wake up your event loop. Then you also don't need a timeout. I.e. you should make your "ask to exit" code use the same wakeup mechanism as the work queue, which is what I said at the beginning. Not burning CPU polling a volatile bool in memory on the side.
- a-dub 1y ago> This is the stupid part. You will burn CPU cycles waking up spuriously for timeouts with no work to do. Setting the flag won't wake up the event loop until the timeout hits, adding pointless delay. it's the smart part. waking up at 50hz or 100hz is essentially free and if there's an os bug or other race that causes the one time "wake up to exit" event to get lost, the system will still be able to shut down cleanly with largely imperceptible delay. it also means that it can be ported to systems that don't support combined condition variable/fd semantics.
- deleted 1y ago[deleted]
- loeg 1y ago> You want to make signalling an exit to actually wake up your event loop. This is exactly what condwait + condsignal do.