samcrow / rust-xplm

Rust interfaces to the X-Plane plugin SDK
Apache License 2.0
41 stars 17 forks source link

(Tokio) Threading #9

Open MTRNord opened 3 years ago

MTRNord commented 3 years ago

Hi I am currently wanting to write a plugin and get stuck. Its a plugin to send certain Datarefs constantly to an external DB. Therefor I would like to run the actual work in another thread. However the DataRef type is non Send making usage with tokio impossible. Cause for this is likely the pointer in DataRef. Is that intended or can the API be cleared up to allow usage with tokio?

samcrow commented 3 years ago

Based on this blog post, the dataref access functions can only be called from the plugin callbacks, not from any other threads. That means that DataRef needs to not be Send, as a way to partially enforce that rule.

As a workaround, I would look for a way to move the values from the plugin callback to the thread that does the sending.

MTRNord commented 3 years ago

Hm interesting. I made it work now with a Arc<RwLock<DataRef<>>> and manually defining the wrapper struct as Send and Sync ( https://github.com/MTRNord/xplane-datamonitor/blob/main/src/energy.rs#L10-L16 ).

And this seems to work atleast just fine for reading. (Which for me is all needed currently). As this code runs flawless: https://github.com/MTRNord/xplane-datamonitor/blob/main/src/lib.rs#L37-L63

So I guess this only actually affects writing as this may lead to race conditions 🤔 makes sense (somehow)

(Note I am aware this is probably not the intended way)

MTRNord commented 3 years ago

For the record: In my case i probably should use https://docs.rs/xplm/0.3.1/xplm/flight_loop/index.html anyway and then do http stuff on the other thread instead :) that seems to make more sense for my goal. That would eliminate all issues too