Race condition in wand.c
Posted: 2009-03-18T06:37:07-07:00
I'm using Magick++ in a multithreaded C++ Program, and noticed a race condition between AcquireWandId and RelinquishWandId, that sometimes leads to a segfault:
The version I'm using is 6.5.0.1.
- Thread1 holds a Wand.
- Thread2 wants to acquire one, enters AcquireWandId, and runs past the "wand_ids==NULL"-Check (its still valid).
- context switch.
- Thread1 releases his wand, and RelinquishWandId deallocates the SplayTree and the mutex, since this was the last wand in use.
- Thread2 now runs AcquireSemaphoreInfo, thus creating a fresh semaphore, increments "i", and then calls AddValueToSplayTree with a null-pointer as argument.
Code: Select all
WandExport unsigned long AcquireWandId(void)
{
static unsigned long
id = 0;
AcquireSemaphoreInfo(&wand_semaphore);
if ((wand_ids == (SplayTreeInfo *) NULL) &&
(instantiate_wand == MagickFalse))
{
wand_ids=NewSplayTree((int (*)(const void *,const void *)) NULL,
(void *(*)(void *)) NULL,(void *(*)(void *)) NULL);
instantiate_wand=MagickTrue;
}
id++;
(void) AddValueToSplayTree(wand_ids,(const void *) id,(const void *) id);
RelinquishSemaphoreInfo(wand_semaphore);
return(id);
}