I like Unicorn because it’s Unix

我很喜欢这篇文档:I like Unicorn because it’s Unix. 作者重新提起了Unix的设计原则,fork, pipe, exec… 老的就是经典的。作者认为Threads are out:

There’s another problem with Unix programming in Ruby that I’ll just touch on briefly: Java people and Windows people. They’re going to tell you that fork(2) is bad because they don’t have it on their platform, or it sucks on their platform, or whatever, but it’s cool, you know, because they have native threads, and threads are like, way better anyways.

Fuck that.

Don’t ever let anyone tell you that fork(2) is bad. Thirty years from now, there will still be a fork(2) and a pipe(2) and a exec(2) and smart people will still be using them to solve hard problems reliably and predictably, just like they were thirty years ago.

MRI Ruby people need to accept, like Python (you have seen multiprocessing, yes?), that Unix processes are one of two techniques for achieving reliable concurrency and parallelism in server applications. Threads are out. You can use processes, or async/events, or both processes and async/events, but definitely not threads. Threads are out.

我同样不喜欢Unix的threading. Unicorn是一个prefork服务器,跟Apache的prefork工作模式一样(Unicorn的作者我打过交道)。关于prefork有许多巧妙的设计,在经典著作Unix Network Programming里有提及。当然多进程的prefork与事件驱动的服务器各有擅长,它们适用于不同场景。


Instead of a blocking accept(2), Unicorn uses a blocking select(2) with an error pipe and a timeout so that it can bust out and do some other basic housekeeping, like reopening logs, processing signals, and maintaining a heartbeat with the master process.

If select(2) returns due the first condition, the child process calls Socket#accept_nonblock on the shared listening socket, which either returns a newly established connection or fails with Errno::EAGAIN, signaling that some other child process beat us to the accept(2). In either case, accept returns immediately and does not block.

This is just one of many beautiful Unix idioms you’ll find in Unicorn. The signal handling, hot process replacement/reloading with rollback, the SELF_PIPE IPC technique, and the fchmod(2) based heartbeat implementation are at least as interesting. Check it out.


此条目发表在Common分类目录,贴了, 标签。将固定链接加入收藏夹。