multithreading - Rust 中的线程之间共享无锁资源

标签 multithreading rust

我正在将我的 C++ 国际象棋引擎移植到 Rust 中。我有一个在搜索线程之间共享的大哈希表,并且在 C++ 版本中该表是无锁的;没有用于共享读/写访问的互斥体。这是the theory ,如果您有兴趣。

在此代码的 Rust 版本中,它工作正常,但使用了 Mutex:

let shared_hash = Arc::new(Mutex::new(new_hash()));

for _ in 0..n_cpu {
    println!("start thread");
    let my_hash = shared_hash.clone();
    thread_pool.push(thread::spawn(move || {
        let mut my_hash = my_hash.lock().unwrap();
        let mut search_engine = SearchEngine::new();
        search_engine.search(&mut myhash);
    }));
}

for i in thread_pool {
    let _ = i.join();
}

如何在没有互斥体的情况下在线程之间共享表?

最佳答案

实际上很简单:如果底层结构已经同步,则不需要互斥体

在您的情况下,例如原子结构数组就可以工作。您可以找到 Rust 的可用原子 here .

关于multithreading - Rust 中的线程之间共享无锁资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39704003/

相关文章:

java - Spring Batch 的 ItemWriter 是单例类吗?

Java 7 的 fork/join 框架没有使用所有可用的 CPU 能力

rust - 有条件地从二进制堆中弹出元素时,借用检查器不满意

rust - 当任何任务正在运行时,如何阻止异步程序终止?

rust - 当忽略某些值时,如何避免迭代器实现中不必要的昂贵操作?

ios - Swift:更新 UI - 主线程上的整个功能或只是 UI 更新?

java - 使用java在n秒内检查和处理一次

rust - 是否有等同于 Haskell 在 Rust 中迭代的东西?

c++ - std::rethrow_exception 因嵌套线程而失败

windows - 为什么 usize::max_value() 在 64 位 Windows 上返回无符号 32 位整数的最大值?