问题描述
我需要一些帮助来了解Ruby 1.8.7中的Hash.
I need some help in understanding Hash in Ruby 1.8.7.
我有一个多线程Ruby应用程序,大约95%的时间该应用程序的多个线程正尝试访问全局哈希.
I have a multi-threaded Ruby application, and about 95% of time multiple threads of the application are trying to access a global Hash.
我不确定默认的Ruby Hash是否是线程安全的.拥有快速哈希的最佳方法是什么,但根据我的情况又是线程安全的?
I am not sure if the default Ruby Hash is thread safe. What would be the best way to have a fast Hash but also one that is thread safe given my situation?
推荐答案
我建议使用可读写锁保护Hash
的包装器.我找不到预构建的Ruby读写锁实现(当然JRuby用户可以使用java.util.concurrent.ReentrantReadWriteLock),所以我构建了一个.您可以在以下位置查看它:
I would suggest a wrapper which protects the Hash
with a read-write lock. I couldn't find a pre-built Ruby read-write lock implementation (of course JRuby users can use java.util.concurrent.ReentrantReadWriteLock), so I built one. You can see it at:
https://github.com/alexdowad/showcase/blob/master/ruby-threads/read_write_lock.rb
我和另外两个人在MRI 1.9.2,MRI 1.9.3和JRuby上进行了测试.它似乎工作正常(尽管我仍然想进行更彻底的测试).它具有内置的测试脚本;如果您有多核计算机,请下载并尝试运行它,并让我知道结果!就性能而言,在有读取偏差的情况下,它会击败Mutex.即使在写入次数达到80-90%的情况下,它的 still 似乎也比使用Mutex快一点.
Me and two other people have tested it on MRI 1.9.2, MRI 1.9.3, and JRuby. It seems to be working correctly (though I still want to do more thorough testing). It has a built-in test script; if you have a multi-core machine, please download, try running it, and let me know the results! As far as performance goes, it trounces Mutex in situations with a read bias. Even in situations with 80-90% writes, it still seems a bit faster than using a Mutex.
我还计划对Java的ConcurrentHashMap进行Ruby移植.
I am also planning to do a Ruby port of Java's ConcurrentHashMap.
这篇关于快速线程安全的Ruby哈希,具有强大的读取偏差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!