koka-lang / libmprompt

Robust multi-prompt delimited control and effect handlers in C/C++
MIT License
106 stars 11 forks source link

Mutex? #6

Open SchrodingerZhu opened 3 years ago

SchrodingerZhu commented 3 years ago

It seems that the prompt will violate same-thread-lock, same-thread-release rule in some case. (Consider a thread pool to execute multiple prompts). I dont know whether it is my fault so I open this to ask whether the library support that usage currently.

daanx commented 3 years ago

Right, I will add documentation on this. The multi-prompt api is not doing any locking and leaves it up to the programmer. It is generally not safe to resume a resumption from another thread for 2 reasons:

  1. like you observe, you may take mutex and yield up on thread A, and then resume it on thread B which subsequently releases the mutex. Now different threads access the mutex.
  2. also, you may start on threead A, and resume on thread B; now when B yields up it may be that that operation executes in a stack that originated on thread A but is now running the context of thread B. That may give trouble if there is a dependency on thread local state.

So, generally one must be very careful to migrate resumptions between threads. It is possible though in principle if the right guarantees are given, in particular if it is used from the outermost handler (for example, this would be the case for asynchronous I/O or a green-threading library)