views:

66

answers:

2
+2  Q: 

Threads vs. Async

I have been reading up on the threaded model of programming versus the asynchronous model from this really good article. http://krondo.com/blog/?p=1209

However, the article mentions the following points.

  1. An async program will simply outperform a sync program by switching between tasks whenever there is a I/O.
  2. Threads are managed by the operating system.

I remember reading that threads are managed by the operating system by moving around TCBs between the Ready-Queue and the Waiting-Queue(amongst other queues). In this case, threads don't waste time on waiting either do they?

In light of the above mentioned, what are the advantages of async programs over threaded programs?

+1  A: 

First of all, note that a lot of the detail of how threads are implemented and scheduled are very OS-specific. In general, you shouldn't need to worry about threads waiting on each other, since the OS and the hardware will attempt to arrange for them to run efficiently, whether asynchronously on a single-processor system or in parallel on multi-processors.

Once a thread has finished waiting for something, say I/O, it can be thought of as runnable. Threads that are runnable will be scheduled for execution at some point soon. Whether this is implemented as a simple queue or something more sophisticated is, again, OS- and hardware-specific. You can think of the set of blocked threads as a set rather than as a strictly ordered queue.

Note that on a single-processor system, asynchronous programs as defined here are equivalent to threaded programs.

Joe Kearney
+2  A: 
  1. It is very difficult to write code that is thread safe. With asyncronous code you know exactly where the code will shift from one task to the next and race conditions are much therefore much harder to come by.
  2. Threads consume a fair amount of data since each thread needs to have its own stack; with async code all the code shares the same stack and the stack is kept small due to continuously unwinding the stack between tasks.
  3. Threads are OS structures and are therefore more memory for the platform to support. There is no such problem with asynchronous tasks.
doron