开发者

Ruby programming style: Asynchronous message passing

Hopefully this is not too subjective...

I am new to the idea of asynchronous message-based programming -- in other words, writing a collection of self-sufficient "mini-programs" that all run simultaneously and only act in response to messages receive开发者_高级运维d.

I understand that this style necessarily uses up a lot of CPU cycles.


Other than that, what can be said for and against the async message-passing style?


This kind of programming is primarily useful for solving a certain class of problems; mainly those that need to handle many connections while only doing a small amount of work. Telecommunications switches, stock exchanges, and instant messenger servers naturally come to mind, but those that are clever can use the pattern for a lot of different things.

One of the big advantages to this approach turns out to be distributivity: instead of running all those processes on a single machine (where having more processes than processors usually won't do you much good), you can easily distribute them evenly across many machines, and have them communicate via a network. This allows for great scalability, such as for a telecommunications switchboard or an electronic stock exchange, where great amounts of little bits of information need to be handled quickly and efficiently.

On the other hand, this approach doesn't work well for programs that don't break-up into little pieces, and doesn't help at all when a single user is using the application and the event loop is small. A good example of this is pretty much any desktop application you have. You don't gain anything from your word processor running over a large number of processes because 99.9% of the time is spent event handling the last key press and it is complete before your next key press, but you do loose time spent in the overhead of managing the processes and the messaging queues.

All that aside, there is one other big issue with asynchronous applications: shared data. One can look at the classic multithreading problem: Let's say your app is an bank server handling ATM transactions. Without a lock on the account balance, if a husband and wife are both depositing paychecks simultaneously, they could collide with eachother's operations and become short changed! By using asynchronous processing agents, you have to do a lot of work to make sure these cases are handled correctly, and sometimes the obvious/easy solution (such as locks) can have the adverse effect of bottlenecking or even linearizing the code execution so that no benefit was gained over a single application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜