【问题标题】:Rust equivalent code for this C++ mutex code此 C++ 互斥代码的 Rust 等效代码
【发布时间】:2020-05-03 17:01:47
【问题描述】:

互斥量和线程示例 互联网不好,因为我无法找到如何使用互斥锁锁定代码块来锁定方法。

// mutex example
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex

std::mutex mtx;           // mutex for critical section

void print_block (int n, char c) {
  // critical section (exclusive access to std::cout signaled by locking mtx):
  mtx.lock();
  for (int i=0; i<n; ++i) { std::cout << c; }
  std::cout << '\n';
  mtx.unlock();
}

int main ()
{
  std::thread th1 (print_block,50,'*');
  std::thread th2 (print_block,50,'$');

  th1.join();
  th2.join();

  return 0;
}

这个 C++ sn-p 的类似 Rust 代码是什么?在 Rust 示例中锁定循环和打印,互斥锁必须是那种类型,例如

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let data = Arc::new(Mutex::new(vec![1u32, 2, 3]));

    for i in 0..3 {
        let data = data.clone();

        thread::spawn(move || {
            let mut data = data.lock().unwrap();
            data[i] += 1;
        });
    }
    thread::sleep_ms(50);
}

【问题讨论】:

  • 这个 c++ sn-p 的 rust 类似代码,锁定循环和打印,如 rust 示例中的互斥锁必须是该类型的互斥锁,例如使用 std::sync::{Arc, Mutex};使用标准::线程; fn main() { 让数据 = Arc::new(Mutex::new(vec![1u32, 2, 3])); for i in 0..3 { let data = data.clone(); thread::spawn(move || { let mut data = data.lock().unwrap(); data[i] += 1; }); } 线程::sleep_ms(50); }
  • edit您的问题添加问题。
  • @idclev463035818 完成
  • 看来How can I lock the internals of my Rust data structure? 的答案可能会回答您的问题。如果没有,请edit您的问题来解释差异。否则,我们可以将此问题标记为已回答。
  • 您在寻找Stdout::lock吗?

标签: multithreading rust mutex


【解决方案1】:

我写过类似的代码。写得好还是可以写得更好?

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let mtx = Arc::new(Mutex::new(""));

    let mtx1 = mtx.clone();

    let mtx2 = mtx.clone();

    let n = 50;

    let th1 = thread::spawn(move || {
        mtx1.lock().unwrap();

        printData(n, "*".to_string());
    });

    let th2 = thread::spawn(move || {
        mtx2.lock().unwrap();

        printData(n, "$".to_string());
    });

    th1.join();
    th2.join();
}

fn printData(n: u32, c: String) {
    let mut str_val: String = "".to_string();

    for i in 0..n {
        str_val.push_str(&c);
    }

    println!("{}", str_val);
}

【讨论】:

  • 当你需要一个不保护任何东西的锁时,你可以使用() aka unit type。
  • 对于工作代码的评论有codereview.stackexchange.com
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多