[SDL] What are threads allowed to do?

Albert Cahalan albert at users.sf.net
Sun Jan 23 09:38:40 PST 2005

On Sun, 2005-01-23 at 12:05, Stephane Marchesin wrote:
> Albert Cahalan wrote:
> >>>I tried using threads, hit memory corruption problems, and...
> >>>
> >>Well, show us a small program demonstrating memory corruption with SDL 
> >>threads, and we'll have a chance to find the reason for this problem.
> >>
> >
> >That's a tough order to fill I think.
> >
> >I saw the problem in Tux Paint, which is one 15469-line file.
> >(yes, yes, we know -- it grew over time)
> >
> We usually ask this because it works.
> That said, if you happen to have a test case demonstrating a precise 
> problem, don't hesitate.
> >
> >One thread was using libSDL_ttf. It scanned through about 200
> >font files. The thread would open a file, render some test text,
> >and close the file.
> >
> >Meanwhile, the main app thread was mostly loading PNG images.
> >It would load a few hundred perhaps, along with a couple fonts
> >and perhaps dozens of *.wav files. The main thread has video
> >and sound going.
> >
> I quickly looked at the file and I think you'll really have a hard time 
> getting it to work, there are too many global variables, whereas I 
> couldn't spot any mutex. Threaded programming must be thought about at 
> the beggining...

What, the tuxpaint.c file? The font thread was supposed to do
a very isolated task. The globals in use by the font thread
would not be touched by the main thread while the font thread
was running, except for reading one "volatile long" that the
font thread sets to indicate completion. The main thread would
do other stuff for a while, then display a progress bar while
waiting for font thread completion. When the font thread is done,
the main thread joins with it before using the global data.

That all worked pretty well, except for memory corruption.
Since the threads don't race on shared globals, there should
not be any need for a mutex. (where would you put it?)

Well, there is a known memory corruption bug in libSDL_ttf
involving italic fonts. It normally doesn't cause trouble,
but maybe the altered memory layout of the threaded solution
(different stack location, etc.) made the problem worse.
Perhaps Tux Paint even has a similar problem, though it
tolerates linking with Electric Fence (a malloc bounds checker)
just fine.

It's looking now like I will use fork(), with a socket to
send back the list of font files. Windows is without fork(),
so the Windows users will just have to wait 20 seconds for
Tux Paint to start. (nothing unusual for them I think)

More information about the SDL mailing list