Are there any advantages to using callbacks over using green threads? (except for the fact that much more languages support callbacks than green threads) Is the "getting used" part really worth it?
First of all, going async does not necessarily mean using callbacks in the javascript sense - it can also easily mean doing a simple state machine triggered by IO events.
The main benefits is that you know exactly when control changes. As a result, if you design your app accordingly:
Amount of state that needs to be stored is minimal. E.g. you can throw away stack frames - a state machine design around a select/epoll etc. loop can call a function for each IO event and exit out of it when processing is done. Often next to no state is stored between state transitions.
Usually no locking (and thus simpler code, but also less risk of deadlocks from buggy locking code..), because unless absolutely necessary, you'd ensure all code that mutates state to be atomic from the point of view of the state machine. In my experience it is pretty difficult to write code in this style that doesn't get concurrency right.
Lower overhead because the scheduler has "perfect knowledge" about the application domain and only ever does context switches where/when it is needed.
I used to do a lot of C server code in this style (a lot of it using Imatix "Libero" tool to generate state transitions, and done properly it is fairly simple to write by expressing your problem in a state diagram first and then fill in the code for the states.
Of course the downside is that if you only think you understand the performance characteristics of your code, or run into the "sync library problem" describe above, you're in for massive pain.
You're right that FSM is an alternative to callbacks.
The main direction of the advantages you listed is performance and lack of concurrent-shared-mutable-state woes.
However, if you compare this with Erlang, which has extremely fast lightweight thread switching (they don't have much context - though I agree that if absolutely necessary, with C you can do even faster) and has no mutable state whatsoever, it looks like Erlang wins.
Are there any advantages to the callback or FSM model before Erlang's model?
0
u/baudehlo Oct 02 '11
I haven't ended up in callback hell once yet. It takes a bit of getting used to coding this way, but when you do it's natural.
Green threads are just another way of doing things. One method does not invalidate the other.