---
title: "线程安全的Rails"
author: "andyhu1007"
date: "2010-04-06T21:33:35Z"
tags: []
categories: ["编程语言"]
slug: "rails"
draft: false
lastmod: "2011-12-23T10:42:52Z"
id: 634890
url: "https://andyhu1007.iteye.com/blog/634890"
---

Thread Safe Rails？ 关于线程安全的Rails，请大家慎重采用，具体看这篇文章：[http://m.onkey.org/thread-safety-for-your-rails](Thread%20Safe%20Rails%EF%BC%9F%20%E5%85%B3%E4%BA%8E%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E7%9A%84Rails%EF%BC%8C%E8%AF%B7%E5%A4%A7%E5%AE%B6%E6%85%8E%E9%87%8D%E9%87%87%E7%94%A8%EF%BC%8C%E5%85%B7%E4%BD%93%E7%9C%8B%E8%BF%99%E7%AF%87%E6%96%87%E7%AB%A0%EF%BC%9Ahttp://m.onkey.org/thread-safety-for-your-rails%E3%80%82%20%20)。

 

上一个项目我们怀着战战兢兢的心情开启了多线程，结果是出乎意料得好。开启多线程后没遇到什么困难，可能会遇到的问题有两点：

 

1\. 去掉class variable (当然，基本上你不应该使用类变量)

 

2\. 另外一件事情，就是在multiple threads下面Rails需要eager load libs。请移步：[http://gigix.thoughtworkers.org/2009/7/17/move-to-multi-threaded-rails](http://gigix.thoughtworkers.org/2009/7/17/move-to-multi-threaded-rails)

 

 

多线程的Rails对于performance有极大提升，请再次移步：[http://blog.headius.com/2008/08/qa-what-thread-safe-rails-means.html](http://blog.headius.com/2008/08/qa-what-thread-safe-rails-means.html)   （请自行fan qiang）

 

**基本上意思是内存使用量的锐减和数据库连接资源的优化:**

 

写道

In a typical Mongrel setup, handling 10 concurrent requests means you have to have 10 copies of Rails loaded, 10 copies of your application loaded, 10 in-memory data caches, 10 database connections...everything has to be scaled in lock step for every additional request you want to handle concurrently.

 

写道

Instead of a single database connection for a given Rails instance, there will be a pool of connections, allowing N database connections to be used by the M requests executing concurrently. It also means allowing requests to potentially execute without consuming a connection, so the number of live, active connections usually will be lower than the number of requests you can handle concurrently.

 

References:

 

教程： [http://m.onkey.org/2008/10/23/thread-safety-for-your-rails](http://m.onkey.org/2008/10/23/thread-safety-for-your-rails)

Slides:  [http://www.slideshare.net/Naoto.Takai/jruby-on-rails-and-thread-safety-presentation](http://www.slideshare.net/Naoto.Takai/jruby-on-rails-and-thread-safety-presentation)   
Q & A: [http://stackoverflow.com/questions/647642/ruby-rails-thread-safety](http://stackoverflow.com/questions/647642/ruby-rails-thread-safety)

 

----EOF----