我正在编写一个音频合成器,想用这个cpal
crate 输出音频。这需要创建一个输出线程,该线程的“数据生成”函数需要实现FnMut(&mut [T], &OutputCallbackInfo) + Send + 'static
。 这OutputCallbackInfo
和当前问题无关。
为了生成音频,我有一个AudioPipeline
结构:
pub struct AudioPipeline {
producer: Box<dyn AudioProducer + Sync>,
modifiers: Vec<Box<dyn AudioModifier + Sync>>,
}
其中AudioProducer
和AudioModifier
是其他一些特征。在 中main
,我创建了这样一个管道,然后使用移动闭包将其发送到生成的线程:
let pipeline = AudioPipeline::new(Box::new(sine), vec![Box::new(asdr)]);
let stream = device
.build_output_stream(
...
move |data: &mut [u8], callback_info: &cpal::OutputCallbackInfo| {
...
pipeline.recv();
...
},
...
);
这里,是采用的pipeline.recv()
一种方法。AudioPipeline
&mut self
代码无法编译,而是出现此错误:
(dyn AudioProducer + Sync + 'static) cannot be sent between threads safely
the trait bound Unique<(dyn AudioProducer + Sync + 'static)>: Send is not satisfied
required for Unique<(dyn AudioProducer + Sync + 'static)> to implement Send
我推测这个问题与使用 ? 有关Box
。但我发现这个错误有点难以理解:毕竟,文档明确指出“[ Unique<T>
] implements Send
/ Sync
if T
is Send
/ Sync
”。既然要求 也是dyn AudioProducer
,Sync
那么它肯定应该是Send
,对吧?我可能忽略了一些线程安全的细微之处。