bf# Channel Features 使用指南
本项目支持通过 Cargo features 在两种不同的 channel 实现之间切换:
## 支持的 Channel 实现
### 1. 标准库实现 (默认)
- 使用 `std::sync::mpsc::channel` (无界 channel)
- 使用 `std::sync::mpsc::sync_channel` (有界 channel)
- 轻量级,无额外依赖
- 适合大多数应用场景
### 2. Crossbeam 实现
- 使用 `crossbeam::channel::unbounded` (无界 channel)
- 使用 `crossbeam::channel::bounded` (有界 channel)
- 更高性能,支持更多高级功能
- 适合高并发、低延迟场景
## 使用方法
### 在 Cargo.toml 中配置
```toml
[features]
default = ["std_lock"]
crossbeam_channel = [] # 启用 crossbeam channel 实现
```
### 编译时选择实现
#### 使用默认的 std 实现:
```bash
cargo build
cargo run
cargo test
```
#### 使用 crossbeam 实现:
```bash
cargo build --features crossbeam_channel
cargo run --features crossbeam_channel
cargo test --features crossbeam_channel
```
### 代码示例
```rust
use fast_able::fast_thread_pool::{channel_types, TaskExecutorUnified};
fn main() {
// 创建 channel(自动根据 feature 选择实现)
let (tx, rx) = channel_types::unbounded::<String>();
// 发送消息
tx.send("Hello".to_string()).unwrap();
// 接收消息
let msg = rx.recv().unwrap();
println!("收到消息: {}", msg);
// 使用统一的任务执行器
let executor = TaskExecutorUnified::new(
core_affinity::CoreId { id: 0 },
-1
);
executor.spawn(|core_id| {
println!("任务在核心 {} 上执行", core_id);
});
}
```
### 运行时检测当前实现
```rust
fn show_channel_implementation() {
#[cfg(feature = "crossbeam_channel")]
println!("使用 crossbeam::channel 实现");
#[cfg(not(feature = "crossbeam_channel"))]
println!("使用 std::sync::mpsc 实现");
}
```
## API 统一性
无论使用哪种实现,API 都是完全一致的:
```rust
// 类型别名
pub type Sender<T> = /* 根据 feature 选择 */;
pub type Receiver<T> = /* 根据 feature 选择 */;
pub type TryRecvError = /* 根据 feature 选择 */;
// 函数接口
pub fn unbounded<T>() -> (Sender<T>, Receiver<T>);
pub fn bounded<T>(cap: usize) -> (Sender<T>, Receiver<T>);
```
## 性能对比
| 编译时间 | 更快 | 稍慢 |
| 运行时性能 | 良好 | 更优 |
| 内存使用 | 标准 | 优化 |
| 功能丰富度 | 基础 | 丰富 |
| 依赖大小 | 无额外依赖 | 需要 crossbeam |
## 选择建议
### 使用 std 实现的场景:
- 简单的应用程序
- 对编译时间敏感
- 希望减少依赖
- 性能要求不高
### 使用 crossbeam 实现的场景:
- 高并发应用
- 对性能要求较高
- 需要更多 channel 功能
- 已经使用了 crossbeam 生态
## 示例程序
运行示例程序来体验不同实现:
```bash
# 使用 std 实现
cargo run --example channel_features_demo
# 使用 crossbeam 实现
cargo run --example channel_features_demo --features crossbeam_channel
```
## 测试
运行测试来验证功能:
```bash
# 测试 std 实现
cargo test --lib test_channel_feature_info
# 测试 crossbeam 实现
cargo test --lib test_channel_feature_info --features crossbeam_channel
```
## 注意事项
1. **编译时选择**:channel 实现在编译时确定,运行时无法切换
2. **API 兼容性**:两种实现的 API 完全兼容,可以无缝切换
3. **性能差异**:在高并发场景下,crossbeam 实现通常性能更好
4. **依赖管理**:crossbeam 实现会增加编译依赖,但不会影响最终二进制大小太多