此c ++互斥锁代码的等效生锈代码

问题描述 投票:-1回答:1

我不熟悉锈和互斥锁,线程示例在互联网,因为我找不到如何锁定代码块使用互斥锁的方法。

    // 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 ++代码段,锁定循环和打印将成为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);
}
multithreading rust mutex
1个回答
-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);
}
© www.soinside.com 2019 - 2024. All rights reserved.