Posted by Seamus on Wednesday, March 30, 2011.

Resque, the rand() method, and Kernel.fork

We had a seemingly impossible number of tmpdir collisions once we switched our reference data web service from DelayedJob to Resque.

The culprit was calling rand() in worker processes that are forked off the main process by Resque:

$ irb
> Kernel.fork { puts rand.to_s }
  0.536506566371644
> Kernel.fork { puts rand.to_s }
  0.536506566371644              # the same
> Kernel.fork { puts rand.to_s }
  0.536506566371644              # the same

Don’t forget to call srand!

$ irb
> Kernel.fork { srand; puts rand.to_s }
  0.232438861240513
> Kernel.fork { srand; puts rand.to_s }
  0.363543277594837
> Kernel.fork { srand; puts rand.to_s }
  0.000133387538081786

Now it’s fixed in the remote_table gem via this commit.

What blog is this?

Safety in Numbers is Brighter Planet's blog about climate science, Ruby, Rails, data, transparency, and, well, us.

Who's behind this?

We're Brighter Planet, the world's leading computational sustainability platform.

Who's blogging here?

  1. Patti Prairie CEO