Why not threads

From C

Jump to: navigation, search

$Id: why_not_threads.txt,v 1.3 2009/02/20 15:18:33 db Exp db $

I would never tell an experienced programmer not to use threads, an experienced programmer will not learn anything new from this document.

Programmers expectations about threads are troublesome; typical ones are:

1) threads will make my program faster!

This one is the most problematic. This makes assumptions about what threads are in the first place. A process has context, can be preempted out of memory and restarted later. light weight threads do not have a heavy context the thread library is essentially another scheduler/program that runs threads as a cooperative multitasking tasks. When any thread needs to do I/O it can block that thread and allow another thread to do some work. Sounds great, until you realise you were really only running one thread in the first place and were only doing threads so you could have simulated asynchronous I/O. So why didn't you do aio in the first place? Why didn't you make your program event driven in the first place? Now instead of a single layer, you and the OS, you have introduced a layer between your application and the OS, which is guaranteed to slow down your program!

2) But, I have a multicore processor I want to run on those other cores!

Again, this makes assumptions about what threads are. If your threads are indeed not light weight threads but have context, (Linux POSIX-threads fit this category) then you might indeed gain some speed if the mutex overhead does not bite you, but now your threads are now competing with other programs running on the machine vying for CPU time. It's not that simple. Add in the additional complexity of a threaded program and it is not certain that your program will run any faster or better and in fact, it is almost guaranteed that your program will run slower.


3) I do multi-processing how can I do that without threads?

It may be that you really do need another process, e.g. one that does your GUI portion of your program and one that does the actual computation. This results in no need to do locking of any sort, you end up sending messages back and forth between the two programs. In short, you are now emulating a multi-tasking OS with message passing. This can be very effective and is rather easier than dealing with locking. It may also be that you can use event driven programming. This is classically what is done with GUIs, an event comes in you deal with it. This is effectively doing cooperative multitasking in one program, only you get to do your own processing as needed.

--Dianora 21:17, 20 February 2009 (UTC)

Personal tools