Clone coroutines

Hi,
is there a way to clone coroutines, or a whole coroutine context?

I have a program that simulates concurrent coordinated stochastic processes as a set of coroutines. In order to implement heuristic search and decision making algorithms (like Monte Carlo Tree Search), I would like to take a current state of execution and clone it multiple times, as a basis for simulating outcomes of multiple possible continued executions.

Is there any way to do this?

Thanks,

Joel

No, it isn’t.

Sure, split your algorithm in steps and provide to each step a cloneable input.

@fvasco, thanks for your reply.

I was hoping that I could encapsulate the process/state of the processes in individual co-routines, i.e., use the implicit state machine underlying the co-routine as a manifestation of the processes’ states.

What you suggest is now to encode the state of the processes explicitly, and then I would have to program the process logic based on this state information, for example using a state-machine pattern.

This is not as elegant as I hoped it could be. I hoped I could use Kotlin to build a DSL for modeling concurrent processes (works), and execute them (works), and analyze then as outlined above (does not work…)

Are you absolutely positive that it is impossible to clone coroutines, or for example to somehow serialize/deserialize them? Somehow access and serialize the continuations representing their progress…?

Writing my last post gave me some more ideas on what to search for, and so I found this discussion here: Serializability of coroutine classes · Issue #76 · Kotlin/kotlinx.coroutines · GitHub

1 Like

There is a discussion of the possibility of “remote continuation”. Namely serialization of the coroutine context. But is just a raw idea right now.

Thanks.
Looks like we have to hope that coroutine serializability will be added in the future.
Where is this discussion about “remote continuations” taking place? – I could not find it.

It is a general discussion that arises from time to time in chats. There are no principal blockers for that, the only problem is to ensure that all CoroutineContext elements and all captured variables are serializable. There is no way to guarantee that right now.

2 Likes

I think that there isn’t a plug&play solution for your task.
Clone an object involves in mutable and immutable entities, shared instances and singleton objects.

If a coroutine uses a logger, should this logger be cloned? The new logger should log in a new file?

I suggest you to reconsider your proposed solution.