Rust lazy_static and tokio::sync::mpsc::channel in tokio::se



我最近开始用rust进行编码,我很喜欢它;"包裹";C-API。在一种情况下,我必须在Rust中定义回调,C可以调用它。我让bindgen创建回调。由于代码需要异步运行,因此我使用tokio。

我想要实现的目标

我将main函数创建为tokio::main。在主函数中,我创建了两个异步任务,一个侦听通道,另一个触发C-API中的消息队列。如果消息可用,我想通过回调函数上的通道发送消息,这样我就可以在任务中接收消息,在任务中我正在侦听事件。稍后,我想通过SSE或GraphQL订阅向几个客户端发送这些消息。

我不能更改C-Callback,因为它们需要可以传递给C-API,而且我必须使用callback,否则我不会收到消息。

我的最新方法看起来是这样简化的:

use lazy_static::lazy_static;
use tokio::sync::{
mpsc::{channel, Receiver, Sender},
Mutex,
};
use bindgen::{notify_connect, notify_connectionstate};
lazy_static! {
static ref BROADCAST_CONNECT: Mutex<(Sender<bool>, Receiver<bool>)> = Mutex::new(channel(128));
static ref BROADCAST_CONNECTIONSTATE: Mutex<(Sender<u32>, Receiver<u32>)> = Mutex::new(channel(128));
}
#[tokio::main]
async fn main() {    
unsafe { notify_connect(Some(_notify_connect)) } // pass the callback function to the C-API
unsafe { notify_connectionstate(Some(_notify_connectionstate)) } // pass the callback function to the C-API
tokio::spawn(async move { // wait for a channel to have a message
loop {
tokio::select! {
// wating for a channel to receive a message
Some(msg) = BROADCAST_CONNECT.lock().await.1.recv() => println!("{}", msg),
Some(msg) = BROADCAST_CONNECTIONSTATE.lock().await.1.recv() => println!("{}", msg),
}
}
});
let handle2 = tokio::spawn(async move {
loop {
unsafe {
message_queue_in_c(
some_handle,
true,
Duration::milliseconds(100).num_microseconds().unwrap(),
)
}
}
});
handle.await.unwrap();
habdle2.await.unwrap();
}
// the callback function that gets called from the C-API
unsafe extern "C" fn _notify_connect(is_connected: bool) {
// C-API is not async, so use synchronous lock
match BROADCAST_CONNECT.try_lock() {
Ok(value) => match value.0.blocking_send(is_connected) {
Ok(_) => {}
Err(e) => {
eprintln!("{}", e)
}
},
Err(e) => {
eprintln!("{}", e)
}
}
}
unsafe extern "C" fn _notify_connectionstate(connectionstate: u32) {
match BROADCAST_CONNECTIONSTATE.try_lock() {
Ok(value) => match value.0.blocking_send(connectionstate) {
Ok(_) => {}
Err(e) => {
eprintln!("{}", e)
}
},
Err(e) => {
eprintln!("{}", e)
}
}
}

问题是:

error[E0716]: temporary value dropped while borrowed
--> src/main.rs:37:29
|
35 | /             tokio::select! {
36 | |                 Some(msg) = BROADCAST_CONNECT.lock().await.1.recv() => println!("{}", msg),
37 | |                 Some(msg) = BROADCAST_CONNECTIONSTATE.lock().await.1.recv() => println!("{}", msg),
| |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
38 | |             }
| |             -
| |             |
| |_____________temporary value is freed at the end of this statement
|               borrow later captured here by closure
|
= note: consider using a `let` binding to create a longer lived value

我理解这个信息以及为什么会发生这种情况,但我想不出解决方案。

我有一个使用横梁通道的工作示例,但我更喜欢使用tokio中的异步通道,所以我没有那么多依赖项,而且一切都是异步的。

工作示例:

use lazy_static::lazy_static;
use crossbeam::{
channel::{bounded, Receiver, Sender},
select,
};
use bindgen::{notify_connect, notify_connectionstate};
lazy_static! {
static ref BROADCAST_CONNECT: (Sender<bool>, Receiver<bool>) = bounded(128);
static ref BROADCAST_CONNECTIONSTATE: (Sender<u32>, Receiver<u32>) = bounded(128);
}
#[tokio::main]
async fn main() {    
unsafe { notify_connect(Some(_notify_connect)) } // pass the callback function to the C-API
unsafe { notify_connectionstate(Some(_notify_connectionstate)) } // pass the callback function to the C-API
let handle1 = tokio::spawn(async move {
loop {
select! {
recv(&BROADCAST_CONNECT.1) -> msg => println!("is_connected: {:?}", msg.unwrap()),
recv(&BROADCAST_CONNECTIONSTATE.1) -> msg => println!("connectionstate: {:?}", msg.unwrap()),
}
}
});
let handle2 = tokio::spawn(async move {
loop {
unsafe {
message_queue_in_c(
some_handle,
true,
Duration::milliseconds(100).num_microseconds().unwrap(),
)
}
}
});
handle.await.unwrap();
handle2.await.unwrap();
}
// the callback function thats gets called from the C-API
unsafe extern "C" fn _notify_connect(is_connected: bool) {
match &BROADCAST_CONNECT.0.send(is_connected) {
Ok(_) => {}
Err(e) => eprintln!("{}", e),
};
}
unsafe extern "C" fn _notify_connectionstate(connectionstate: u32) {
match BROADCAST_CONNECTIONSTATE.0.send(connectionstate) {
Ok(_) => {}
Err(e) => eprintln!("{}", e),
}
}

备选方案

一个我也没有开始工作的替代方案是使用某种本地函数或使用闭包。但我不确定这是否会起作用,甚至是如何起作用。也许有人有个主意。如果这样的东西能起作用,那就太好了,所以我不必使用lazy_static(我宁愿代码中没有全局/静态变量(

use tokio::sync::{
mpsc::{channel, Receiver, Sender},
Mutex,
};
use bindgen::{notify_connect, notify_connectionstate};
#[tokio::main]
async fn main() {
let app = app::App::new();
let mut broadcast_connect = channel::<bool>(128);
let mut broadcast_connectionstate = channel::<bool>(128);
let notify_connect = {
unsafe extern "C" fn _notify_connect(is_connected: bool) {
match broadcast_connect.0.blocking_send(is_connected) {
Ok(_) => {}
Err(e) => {
eprintln!("{}", e)
}
}
}
};
let notify_connectionstate = {
unsafe extern "C" fn _notify_connectionstate(connectionstate: u32) {
match broadcast_connectionstate.0.blocking_send(connectionstate) {
Ok(_) => {}
Err(e) => {
eprintln!("{}", e)
}
}
}
};
unsafe { notify_connect(Some(notify_connect)) } // pass the callback function to the C-API
unsafe { notify_connectionstate(Some(notify_connectionstate)) } // pass the callback function to the C-API
let handle = tokio::spawn(async move {
loop {
tokio::select! {
Some(msg) = broadcast_connect.1.recv() => println!("{}", msg),
Some(msg) = broadcast_connectionstate.1.recv() => println!("{}", msg),
}
}
});
let handle2 = tokio::spawn(async move {
loop {
unsafe {
message_queue_in_c(
some_handle,
true,
Duration::milliseconds(100).num_microseconds().unwrap(),
)
}
}
});
handle.await.unwrap();
handle2.await.unwrap();
}

这种方法的问题

can't capture dynamic environment in a fn item
--> src/main.rs:47:19
|
47 |             match broadcast_connectionstate.0.blocking_send(connectionstate) {
|                   ^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: use the `|| { ... }` closure form instead

如果有人能解决我的任何一个问题,那就太好了。如果这是一种全新的方法,那也没关系。如果频道或tokio或其他什么都不是办法,那也没关系。我主要使用的是tokio,因为我也在使用tokio,所以我不必有更多的依赖关系。

已经谢谢你,一直读到这里。

如果您对第一个示例进行以下更改,它应该可以工作:

  1. tokio::sync::Mutex替换为std::sync::Mutex,这样就不必在回调中使用try_lock
  2. 不要将接收方存储在互斥对象中,只存储发送方
  3. 在回调中,使用无边界通道,或者确保在发送之前释放锁
  4. 使用std::thread::spawn而不是tokio::spawn在专用线程上运行阻塞C代码。(为什么?(

要不将接收器存储在互斥对象中,可以执行以下操作:

static ref BROADCAST_CONNECT: Mutex<Option<Sender<bool>>> = Mutex::new(None);
// in main
let (send, recv) = channel(128);
*BROADCAST_CONNECT.lock().unwrap() = Some(send);

如果您想要一个有界通道,可以先克隆通道,然后在锁上调用drop,然后使用blocking_send进行发送,从而释放锁。对于无边界通道,这并不重要,因为发送是即时的。

// in C callback
let lock = BROADCAST_CONNECT.lock().unwrap();
let send = lock.as_ref().clone();
drop(lock);
send.blocking_send(...);

相关内容

  • 没有找到相关文章

最新更新