Skip to content

Commit

Permalink
protect against potential runtime race condition.
Browse files Browse the repository at this point in the history
suspect there's potential for platform-specific racing on our singular bu_init_lock depending on how static initialization is ordered.  this would explain several issues observed consistently on freebsd (possibly obscure issues on other platforms), but still testing.  the solution is to not rely on static initialization of the mutex, instead resorting to runtime init on first use via pthread_once().
  • Loading branch information
brlcad committed Jan 6, 2025
1 parent 9e96d9d commit ebc54ca
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/libbu/semaphore.c
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,30 @@ struct bu_semaphores {
pthread_mutex_t mu;
};

static pthread_mutex_t bu_init_lock = SEMAPHORE_INIT;
static pthread_mutex_t bu_init_lock;
static pthread_once_t bu_init_once = PTHREAD_ONCE_INIT;
# define DEFINED_BU_SEMAPHORES 1

static void bu_init_lock_init(void)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
int ret = pthread_mutex_init(&bu_init_lock, &attr);
pthread_mutexattr_destroy(&attr);
if (ret) {
fprintf(stderr, "bu_semaphore_acquire(): pthread_mutex_init() failed on init lock\n");
sem_bomb(ret);
}
}

static void ensure_bu_init_lock_initialized(void)
{
/* help ensure thread-safe initialization */
pthread_once(&bu_init_once, bu_init_lock_init);
}


/*
* multithread support based on the Windows kernel.
*/
Expand All @@ -112,7 +133,6 @@ static struct bu_semaphores bu_semaphores[SEMAPHORE_MAX] = {{SEMAPHORE_MAGIC, SE
#endif



void
bu_semaphore_init(unsigned int nsemaphores)
{
Expand Down Expand Up @@ -158,6 +178,8 @@ bu_semaphore_init(unsigned int nsemaphores)
}

# elif defined(HAVE_PTHREAD_H)
ensure_bu_init_lock_initialized();

int ret = pthread_mutex_lock(&bu_init_lock);
if (ret) {
fprintf(stderr, "bu_semaphore_acquire(): pthread_mutex_lock() failed on init lock\n");
Expand Down

0 comments on commit ebc54ca

Please sign in to comment.