Hello Rioters,

I'm trying to figure out how could cooperative multithreading / fibers / coroutines be used in RIOT. There is something already in the scheduler, but right now it looks more like an artifact of the implementation than a proper feature.


Why
---

Pre-emptive threading is hard to reason about, requires locks and synchronization and often there is no real need for pre-emption.

With coroutines, on the other hand, the programmer knows his program wont be interrupted and resumed in any random line, but exactly when he chooses. It also means he does not need to synchronize access to resources shared with other coroutines.

Coroutines make it possible to program asynchronous code in a blocking style - see "await". This is more natural and easier that using callbacks.


Current state in RIOT
---------------------

The current RIOT scheduler will only switch between threads with the same priority if there is an explicit yield, or if there occurs a preemption by a higher priority thread.

This is almost cooperative multithreading (within the same "priority group"), except there is no guarantee that after a thread in a group is preempted, it will be that thread an not another with the same priority that will get resumed. Maybe that is the current behavior, but I'm having some trouble understanding the scheduler code.

Also, the docs explicitly discourage the user from creating threads with the same priority. From "thread.h":

> Assigning the same priority to two or more threads is usually not a
> good idea.


Starting point
--------------

A good starting point would be to guarantee threads with the same priority get cooperatively scheduled 100% of the time. This means that if one thread is preempted by a higher priority task, then no other thread but that one will get resumed. In other words, the only way to switch between threads with the same priority is explicitly yielding from one.

Maybe this is the current behavior. As I mentioned, I don't quite understand the code.


Further development
-------------------

Coroutines / Fibers do not have to be full fledged threads. The TCB can be simpler and some objects can be shared with other fibers. See the PR on a thread-safe implementation of newlib (https://github.com/RIOT-OS/RIOT/pull/8619) for an idea of the overhead that thread-safety imposes.



What is the general opinion on this? Is it work pursuing?

I look forward to you feedback.

Regards,

Juan.
_______________________________________________
devel mailing list
[email protected]
https://lists.riot-os.org/mailman/listinfo/devel

Reply via email to