tock / libtock-rs

Rust userland library for Tock
Apache License 2.0
164 stars 109 forks source link

Safe concurrency #27

Closed Woyten closed 6 years ago

Woyten commented 6 years ago

I am currently trying to make the callback API more thread safe by via SubscribableCallback: Send.

As expected, I am not able to share any mutable state between a callback and the main thread. This would require a type like std::sync::Mutex which is not available for Tock.

My idea would be to write some simple Tock compatible Mutex type that manages a lock and yields when a lock situation is encountered.

What do you think? Is this a good idea? Is it easily feasible? Maybe there is some library support for it?

brghena commented 6 years ago

In Tock, the architecture of application callbacks is such that callbacks only occur after the application calls yield. They can never occur in the middle of data access. This means a mutex shouldn't actually be necessary for data items used in both the callback and main thread, since their execution is already mutually exclusive as guaranteed by the OS.

Is the problem here that we have no way of specifying to Rust that data accesses are thread safe, or am I misunderstanding the problem?

Woyten commented 6 years ago

Thanks for your response! To be honest, this surprises me. Could you have a look at the button_subscribe example? We loop at the end of the program without yielding. The callback is executed whenever you press a button. Doesn't that mean that the main thread is interrupted?

Woyten commented 6 years ago

Or is it because sleep is yielding? Hmm...

brghena commented 6 years ago

Yup! sleep yields.

Woyten commented 6 years ago

Closed because the Tock architecture is cool!

brghena commented 6 years ago

I would be careful though. This architecture definitely does not solve all problems. Particularly, if you yield inside a callback, you can end up re-entrancy problems which may need some form of locking.

Woyten commented 6 years ago

Is it a problem we can solve in Rust?