rust:线程

1线程

类似于c++,创建线程可以直接传入已经定义的函数,也可以传入闭包,rust中的闭包和c++中的lambda表达式类似。c++中的lambda表达是可以捕获数据,引用捕获和值捕获都可以;rust中的闭包,需要通过move。

本例子中,handle2如果只用到msg的话,不需要move捕获,为什么?

rust 复制代码
use std::thread;
use std::time::Duration;

fn hello_thread() {
  println!("hello thread");
}

fn print_message(msg: String) {
  println!("msg: {}", msg);
}

fn main() {
  let handle1 = thread::spawn(hello_thread);

  let handle2 = thread::spawn(|| {
      for i in 1..10 {
        println!("hi number {} from this spawned thread2!", i);
        thread::sleep(Duration::from_millis(1));
      }
    }
  );

  let msg = String::from("hello rust thread");
  let v = vec![1, 2, 3];
  let handle3 = thread::spawn(move || {
      print_message(msg);
      println!("Here's a vector: {:?}", v);
    }
  );

  for i in 1..5 {
    println!("hi number {} from the main thread!", i);
    thread::sleep(Duration::from_millis(1));
  }

  handle1.join().unwrap();
  handle2.join().unwrap();
  handle3.join().unwrap();
}

2通道channel

类似于go语言,go语言中也有channel。

rust 复制代码
use std::thread;
use std::sync::mpsc;
use std::time::Duration;

fn main() {
  let (tx, rx) = mpsc::channel();
  let tx1 = mpsc::Sender::clone(&tx);

  let handle1 = thread::spawn(move || {
    let vals = vec![String::from("hello"), String::from("thread1")];
    for val in vals {
      tx.send(val).unwrap();
      thread::sleep(Duration::from_secs(1));
    }
  });

  let handle2 = thread::spawn(move || {
    let vals = vec![String::from("hello"), String::from("thread2")];
    for val in vals {
      tx1.send(val).unwrap();
      thread::sleep(Duration::from_secs(1));
    }
  });

  for recv in rx {
    println!("recv {}", recv);
  }

  handle1.join().unwrap();
  handle2.join().unwrap();
}

3多线程加锁

c++中的锁和数据时分离的,而rust中的锁和数据时集成到一块的。

rust 复制代码
use std::sync::{Mutex, Arc};
use std::thread;

fn main() {
  let counter = Arc::new(Mutex::new(0));
  let mut handles = vec![];

  for _ in 0..10 {
    let counter = Arc::clone(&counter);
    let handle = thread::spawn(move || {
      let mut num = counter.lock().unwrap();
      *num += 1;
    });
    handles.push(handle);
  }

  for handle in handles {
    handle.join().unwrap();
  }

  println!("result {}", *counter.lock().unwrap());
}
相关推荐
geovindu10 分钟前
rust: pool Pattern
开发语言·后端·设计模式·rust·对象池简写模式
jimy132 分钟前
标准的动态类型定义与“多态”无关,非多态对象同样会出现动态类型不同于静态类型的情形
开发语言·c++
冬、不眠的夜33 分钟前
Nuitka 将 python 程序编译成 exe 指南
开发语言·python
CVer儿35 分钟前
起源1引擎相关知识点2--World Brush+func_detail
开发语言
Source.Liu1 小时前
【A11】客户端登录流程笔记
windows·rust
薛之谦_1 小时前
JAVA 多线程编程:从基础原理到实战应用
java·开发语言
LMT_Lanmantech1 小时前
Creo许可降本增效:不增购,也能让现有许可发挥更大价值
java·大数据·开发语言
蜗牛互联网1 小时前
Python Agent 工具调用:审批令牌、参数白名单和累计预算
java·开发语言·人工智能·windows·后端·python
承渊政道2 小时前
【Python编程—从入门到实践】(让程序记得、恢复并解释失败:Python 文件、异常与JSON系统教程)
开发语言·python·pycharm·json·异常处理
一水鉴天2 小时前
声调韵的序:从古汉语音韵到系统科学语言的场效应推演 20261013(千问)
开发语言·人工智能