Kotlin / kotlinx.coroutines

Library support for Kotlin coroutines
Apache License 2.0
13.09k stars 1.85k forks source link

Discrete event simulation and custom event loop support #3229

Closed multun closed 2 years ago

multun commented 2 years ago

Hello :wave:

I'd like to contribute a discrete event simulation library which seamlessly integrates with kotlinx coroutines. This issue is about making it possible to implement it using the public API only.

I made a proof of concept, which revealed a few obstacles:

Context

How discrete event simulations work

They typically have an event loop, a virtual clock, a queue of callbacks for the current time, and a sorted queue of events (a timeline). Each event has a time at which it should occur, and a callback.

The algorithm implemented in my proof of concept goes as follows:

dkhalanskyjb commented 2 years ago

Hi! It's cool that people are using coroutines in such a manner.

I looked through your POC and want to mention that what you're doing looks very much like what's going on in the test module: https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test In essence, it's a way to run coroutines using controllable virtual time, with additional safeguards against the occasional code that runs in a forked-off computation. Maybe you could use that or borrow some ideas from there?

Now, we do warn people not to use the test module anywhere but in tests, as the results of using it in production can be surprising, brittle and unpredictable. The most glaring issue would be that the virtual time can easily get out of sync with the real time, leading to all sorts of confusing scenarios when you have to interact with some other systems. This is one of the reasons why Delay is marked as internal. However, given that you already abuse the notion of delay not to mean real time, there's not much else, it seems, that can go wrong.

qwwdfsad commented 2 years ago

Thanks for the interest! We are not ready to accept it as kotlinx.coroutines module and would like to see it as a standalone library.

We are open to discussion for further opening our API and creating additional extension points, so feel free to create issues specific to a particular internal API