Skip to content

通道(channel)的使用 #7

@wuyuedefeng

Description

@wuyuedefeng
  • mpsc 多个生产者单个消费者
  • spmc 单个生产者多个消费者

多生产者单消费者demo

use std::sync::mpsc;
use std::thread;

fn main() {
    let mut handlers = vec![];
    let (tx, rx) = mpsc::channel();
    for idx in 0..3 {
        let tx = tx.clone();
        let handler = thread::spawn(move || {
            for idx2 in 0..3 {
                let message = format!("thread: {}, idx: {}", idx, idx2);
                println!("{}", message);
                tx.send(message).unwrap();
            }
        });
        handlers.push(handler);
    }

    for handler in handlers.into_iter() {
        handler.join().unwrap();
    }

    // 将多余的txdrop掉,其他被clone的tx被释放完毕,rx将结束获取消息,并退出程序
    // drop(tx);
    for msg in rx {
        println!("recv: {}", msg);
    }

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions