0

I have a future that reads from a socket via OS API. My current implementation spawns an internal thread, which polls the socket and calls the waker when there is some ready data. This internal thread seems to me an unnecessary overhead.

How to call the waker without involving additional threads?

I was thinking to call the waker immediately each time even if there would be no data to read, but this might spin the processor. It feels not right.

Another way would be to use underlying OS API to set a timer, which would interrupt some existing thread with a callback or a message. It feels like it would work, although I didn't try it yet.

Is there an established good way to call the waker without involving internal threads and without using task system specific futures like tokio::time?

nicolai
  • 1,140
  • 9
  • 17
  • Why are you polling yourself? Usually something like `select` is used to be informed when data is ready, and usually the event loop already does that. – MisterMiyagi Apr 20 '23 at 05:09
  • The event loop? Do you mean the event loop of an Executor, like the one in `tokio`? I'm not in control of the event loop. The only way I know to interact with an executor in a generic way (I mean without hardly coupling with it) is via Waker and Context. Do you mean it is possible to instruct an Executor to poll my future if it detects some ready IO events? I wouldn't want my future be dependent on specific Executor, that is why I'm trying to use only the standard futures API. – nicolai Apr 20 '23 at 05:54
  • That's not an answer, but you might want to see how it is done in `mio`. – Cerberus Apr 20 '23 at 08:14
  • @Cerberus IIRC `mio` does not use futures because it does not control the runtime. – Chayim Friedman Apr 20 '23 at 11:04
  • 1
    Unfortunately, I think this is impossible if you don't control the event loop. In `tokio`, for example, the IO futures register an IO event in the runtime driver and the runtime takes care to wake them once the data is ready. – Chayim Friedman Apr 20 '23 at 11:04
  • You could spawn one dedicated thread for all your OS sockets and do a select/poll loop there that calls the waker. I think that is more or less what tokio does, but you should be able to live with the tokio runtime plus your own thread-waker. – rodrigo Apr 20 '23 at 12:00

0 Answers0