Rust code: demo of message system

本文介绍了使用Rust中的mpsc库和hashtable实现一个多线程的消息传递系统,包括创建信道、发送和接收消息,以及处理并发限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Requirements:

1. Multi-threads receive/send messages

2. Use mailbox ID to find message channel

Implementation:

1. use mpsc lib for message channel

2. use hash table for ID to message channel mapping

Limitation:

1. mpsc channel has sender and receiver, but only sender could be clone() in rust. So only sender could be saved in hash table. refer to limitation 2.

2. To share hash table among tasks, need Arc and Mutex for hash table. But the lock range impacts sender's function. To make multi-tasks can work at the same time( not need wait for one task finishing all job then release lock), we need drop the lock of hash table. And only sender could support this drop.

Code:

1. message_lib.rs

use once_cell::sync::Lazy;

use std::vec::Vec;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, mpsc};
//use std::thread;
//use std::time::Duration;


pub struct MessageHeader{
    pub src_id: u32,
    pub dest_id: u32,
    pub primitive: u32,
    pub param: Vec<u32>,
}

// Define a struct to hold the senders with IDs
pub struct MailboxRegistry {
    senders: HashMap<u32, mpsc::Sender<MessageHeader>>,
}

impl MailboxRegistry {
    pub fn new() -> Self {
        MailboxRegistry {
            senders: HashMap::new(),
        }
    }

    pub fn add_mailbox(&mut self, id: u32, sender: mpsc::Sender<MessageHeader>) {
        self.senders.insert(id, sender);
    }

    pub fn get_mailbox_sender(&self, id: u32) -> Option<&mpsc::Sender<MessageHeader>> {
        self.senders.get(&id)
    }
}

pub static MAILBOX_MATRIX: Lazy<Arc<Mutex<MailboxRegistry>>> = Lazy::new(|| {
    Arc::new(Mutex::new(MailboxRegistry::new()))
});

pub struct MailboxSystem {
    //pub ch_matrix : MailboxRegistry,
}

impl MailboxSystem {

    pub fn create_mailbox_channel(id: u32) -> mpsc::Receiver<MessageHeader> {
        let (sender, receiver) = mpsc::channel();
        {
            MAILBOX_MATRIX.lock().unwrap().add_mailbox(id, sender);
        }
        println!("Created channel ID {}", id);
        return receiver;
    }

    pub fn mb_send_message(id:u32, msg:MessageHeader)
    {
        println!("try to send message from sender ID {}, trying to get lock()", id);
        let mailbox_registry = MAILBOX_MATRIX.lock().unwrap();
        if let Some(sender) = mailbox_registry.get_mailbox_sender(id) { //self.get_mailbox_channel_sender(id) {
            /*unlock MAILBOX_MATRIX here*/
            let sender_ref = sender.clone();
            drop(mailbox_registry);
            /*then send message*/
            sender_ref.send(msg).unwrap();
            println!("Sent message from sender ID {}", id);
        } else {
            println!("No sender found for ID {}", id);
        }
    }

}

pub fn print_message(msg:&MessageHeader)
{
    println!("messge src {}",msg.src_id);
    println!("messge dest {}",msg.dest_id);
    println!("messge primitive {}",msg.primitive);
    for element in &(msg.param) {
        println!("Element: {}", element);
    }
}

2. main.rs

use std::vec::Vec;
use std::sync::{mpsc};
use std::thread;
use std::time::Duration;

mod message_lib;
use crate::message_lib::{MailboxSystem,MessageHeader,print_message};

pub fn thread_send_message(mailbox_id:u32, src_id:u32, dest_id:u32, primitive:u32)
{
    let mut msg = MessageHeader {
        src_id : src_id,
        dest_id : dest_id,
        primitive : primitive,
        param : Vec::new(),
    };
    msg.param.push(primitive*2);
    MailboxSystem::mb_send_message(mailbox_id, msg);
}
pub fn thread_recv_message(receiver:&mpsc::Receiver<MessageHeader>) -> u32
{
    match receiver.recv() {
        Ok(msg) => {
            print_message(&msg);
            return msg.primitive;
        }
        Err(_) => {
            println!("Receiver fail");
            return 0;
        }
    }
}

fn main() {
    let thread_recv = thread::spawn( move || {
            println!("start Receiver");
            let mut tx_1_done = 0;
            let mut tx_2_done = 0;
            let receiver = MailboxSystem::create_mailbox_channel(1);
            loop {
                let count = thread_recv_message(&receiver);
                if count == 9999 {
                    tx_1_done = 1;
                }
                if count == 8888 {
                    tx_2_done = 1;
                }
                if tx_1_done == 1 && tx_2_done == 1 {
                    break;
                }
            }
    });
    thread::sleep(Duration::from_secs(1));
    let thread_send1 = thread::spawn( move || {
        println!("start Sender1");
        let mailbox_id = 1;
        let mut primitive = 0;
        for _ in 0..500 {
            primitive += 1;
            thread_send_message(mailbox_id,8,9,primitive);
        }
        primitive = 9999;
        thread_send_message(mailbox_id,8,9,primitive);
        thread::sleep(Duration::from_secs(1));
    });
    let thread_send2 = thread::spawn( move || {
        println!("start Sender2");
        let mailbox_id = 1;
        let mut primitive = 500;
        for _ in 0..400 {
            primitive += 1;
            thread_send_message(mailbox_id,12,9,primitive);
        }
        primitive = 8888;

        thread_send_message(mailbox_id,8,9,primitive);
        thread::sleep(Duration::from_secs(1));
    });
    match thread_send1.join() {
        Ok(_) => println!("The send thread1 has finished."),
        Err(_) => println!("An error occurred while joining the thread"),
    }
    match thread_send2.join() {
        Ok(_) => println!("The send thread2 has finished."),
        Err(_) => println!("An error occurred while joining the thread"),
    }
    match thread_recv.join() {
        Ok(_) => println!("The recv thread has finished."),
        Err(_) => println!("An error occurred while joining the thread:"),
    }

}

3. cargo.toml

[package]
name = "message"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
once_cell = "1.4.0"

[lib]
path = "src/message_lib.rs"

### 关于 UniApp 框架推荐资源与教程 #### 1. **Uniapp 官方文档** 官方文档是最权威的学习资料之一,涵盖了从基础概念到高级特性的全方位讲解。对于初学者来说,这是了解 UniApp 架构技术细节的最佳起点[^3]。 #### 2. **《Uniapp 从入门到精通:案例分析与最佳实践》** 该文章提供了系统的知识体系,帮助开发者掌握 Uniapp 的基础知识、实际应用以及开发过程中的最佳实践方法。它不仅适合新手快速上手,也能够为有经验的开发者提供深入的技术指导[^1]。 #### 3. **ThorUI-uniapp 开源项目教程** 这是一个专注于 UI 组件库设计实现的教学材料,基于 ThorUI 提供了一系列实用的功能模块。通过学习此开源项目的具体实现方式,可以更好地理解如何高效构建美观且一致的应用界面[^2]。 #### 4. **跨平台开发利器:UniApp 全面解析与实践指南** 这篇文章按照章节形式详细阐述了 UniApp 的各个方面,包括但不限于其工作原理、技术栈介绍、开发环境配置等内容,并附带丰富的实例演示来辅助说明理论知识点。 以下是几个重要的主题摘选: - **核心特性解析**:解释了跨端运行机制、底层架构组成及其主要功能特点。 - **开发实践指南**:给出了具体的页面编写样例代码,展示了不同设备间 API 调用的方法论。 - **性能优化建议**:针对启动时间缩短、图形绘制效率提升等方面提出了可行策略。 ```javascript // 示例代码片段展示条件编译语法 export default { methods: { showPlatform() { console.log(process.env.UNI_PLATFORM); // 输出当前平台名称 #ifdef APP-PLUS console.log('Running on App'); #endif #ifdef H5 console.log('Running on Web'); #endif } } } ``` #### 5. **其他补充资源** 除了上述提到的内容外,还有许多在线课程视频可供选择,比如 Bilibili 上的一些免费系列讲座;另外 GitHub GitCode 平台上也有不少优质的社区贡献作品值得借鉴研究。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值