I am trying to do a ffi binding, and all the functions imported from c should only be called in current thread. So I want a compiler error in the following code sample when the functions come to another thread. Is it possible?
Thanks.
You can prevent instances from crossing a thread boundary by ensuring they're !Send. To ensure only one thread can call FFI functions, you can do something like this:
I don't quite understand the solution. I tried comment phantom field, and compiler complained about lifttime. So I move ffi from outside into thread closure, and it's ok now whether phantom field exists or not.
The PhantomData prevents any MyFFI object from crossing a thread boundary, and MyFFI::get() ensures that only one MyFFI instance is ever created. In your example, you're creating that instance on the spawned thread instead of the main one, which is still a form of single-threaded operation.