Thread: Multi-threaded
View Single Post
  #9 (permalink)  
Old 08-16-2006, 10:56 PM
brackett brackett is offline
Programmer
 
Join Date: May 2006
Posts: 193
Credits: 0
Rep Power: 11
brackett is on a distinguished road
Default

Quote:
Originally Posted by amac View Post
You're confusing the issue here. Multi-threading at OS level is a seperate issue from multi-threading at process level.

At the process level its often necessary to have a program with multiple threads, even if they don't actually execute concurrently. For example, you might want to listen to console input while also performing some other computation in the background. And that is important here and *now*.
I'm not sure what you mean by confusing multi-threading at OS vs process level. Threads are always a part of a process, and whether that process is owned by your application or the OS is immaterial to the discussion, I think.

Due to context switches and locking on shared data, multithreading your example will likely end up running slower on a single core machine. Does that mean you shouldn't multithread? Not necessarily...performance is rarely a consideration of mine anymore. But, a lot of programmers (unfortunately) have issues designing, debugging, and maintaining multithreaded code. In the best case, you still have a whole class of new and exciting bugs and scenarios to worry about.

Now, you should spin off new threads from the UI thread for long running tasks - but that's somewhat of a special case, where blocking the UI thread has the unfortunate characteristic of blocking window updates and making your app appear hung. But, gratuitously multithreading doesn't make your code faster, doesn't make it any more maintainable, and doesn't lead to more reliable code...why do it, then?

In your example, you have a need to have a long running process that the user can cancel. You have 2 choices; break the long running process in manageable chunks and poll the input in between chunks, or set up a processing thread and an input thread that communicate with a shared data structure. The processing thread will still need to check the shared data structure to catch an abort request (or you could just kill the thread...but that's a bit extreme) and you'll need to add locking semantics to support simultaneous read/writes.

On a single core machine, I'd vote for the single thread solution. It'll likely be faster, and almost definitely be more maintainable. But, on a dual core machine, the 2 threads can be run on independent CPUs - so the multi threaded solution will be faster because the processing thread can take advantage of a dedicated cache with no context switch penalty.
Reply With Quote