[kwlug disc.] how long would it take you to learn threads programming?

Chris Frey cdfrey at foursquare.net
Tue Apr 22 17:21:11 EDT 2008


On Tue, Apr 22, 2008 at 01:35:54PM -0400, Andrew Kohlsmith (lists) wrote:
> I do not believe it will give you enough time to create some 
> truly challenging bugs and give you an opportunity to demonstrate how to 
> identify and correct some of the nastier traps that hit you in multithreaded 
> programming.

I generally try to avoid using threads if possible (and sometimes I've carried
that aversion too far), but whenever I have used them, I don't recall them
being that scary or wild.  Maybe this is due to growing up writing DOS TSRs
for fun and getting burned that way. :-)

Deadlocks and race conditions are really the only two problems that threaded
programming can cause, and by following some mental rules, they can
often be minimized.  I also favour using a language like C++, and wrapping
lock behaviour in RAII classes, as well as hiding the actual locking
inside a class that has threadsafe member functions.

My rules go like this.  I'd be happy to hear other's rules as well.
I'd love to see examples of those "truly challenging bugs" as well, as
I'm sure I'm forgetting certain things. :-)

	- any shared memory gets a lock
	- lock shared memory according to its function or purpose
	- global variables are even more evil than normal, in threaded apps
	- try to avoid locking two mutexes at once in a given function,
		but if you have to, always lock in the same order
		for the entire application.
	- hide any low level thread work behind a well documented API / class

The complexity for avoiding deadlock increases with the size of your
application, even if you have well documented APIs.  When threaded APIs
start depending on other threaded APIs, things can get hairy.  Hopefully
your API dependencies only go in one direction. :-)

I liked the Boost Thread library by William E. Kempf.  The original library
had a documentation set that included some interesting rationale for
his design decisions, which might make for interesting reading whether
you ultimately use C++ or not.  You can read it here:

	http://www.boost.org/doc/libs/1_33_1/doc/html/threads.html

It appears the Boost library has been rewritten for the new C++ standardization
process, and I'm not up to speed with that yet, so I can't comment on it.

- Chris



More information about the KWLUG-Disc mailing list