Wrong tokio runtime when using dlopen #5299
-
SceneI want to use plugins to compose my application by using CodeThere are two parts of my poject. Project Plugin# Cargo.toml
[package]
name = "plugin"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio={version="1.20", features=["full"]}
[lib]
crate-type = ["cdylib", "rlib"] // lib.rs
use std::any::Any;
pub trait PluginTrait: Send + Sync + Any {
fn run(&self);
fn get_aysnc_fn(&self) -> tokio::time::Sleep;
}
struct Plugin;
impl PluginTrait for Plugin {
fn run(&self) {
println!("##Hello##");
}
fn get_aysnc_fn(&self) -> tokio::time::Sleep {
tokio::time::sleep(tokio::time::Duration::from_secs(1))
}
}
#[no_mangle]
pub extern "C" fn create() -> *mut dyn PluginTrait {
let object = Plugin {};
let boxed: Box<dyn PluginTrait> = Box::new(object);
Box::into_raw(boxed)
} Project app[package]
name = "app"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio={version="1.20", features=["full"]}
libloading = "0.7" // main.rs
use std::any::Any;
use libloading::Symbol;
pub trait PluginTrait: Send + Sync + Any {
fn run(&self);
fn get_aysnc_fn(&self) -> tokio::time::Sleep;
}
#[tokio::main]
async fn main() {
let path = "/Users/mason/code/im/rust/demo/plugin/target/debug/libplugin.dylib";
println!("sleep before dlopen");
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
unsafe {
let lib = libloading::Library::new(path).unwrap();
type CreateSymbol = extern "C" fn() -> *mut dyn PluginTrait;
let create_fn: Symbol<CreateSymbol> = lib.get(b"create").unwrap();
let object = create_fn();
let object = Box::from_raw(object);
object.run();
println!("sleep after dlopen");
object.get_aysnc_fn().await;
println!("after sleep");
}
} Result
ProblemI don't know the reason why the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
The current runtime is stored in thread-local storage, but I guess it is probably not shared with the plugin and the plugin side has its own thread-local for the current runtime. |
Beta Was this translation helpful? Give feedback.
The current runtime is stored in thread-local storage, but I guess it is probably not shared with the plugin and the plugin side has its own thread-local for the current runtime.