Code review request: small optimization to localtime.c

Daniel Eischen deischen at freebsd.org
Wed Nov 28 14:42:14 PST 2007


On Wed, 28 Nov 2007, M. Warner Losh wrote:

> Please find enclosed some small optimizations.  I know they make a
> couple lines too long, I'll correct that before I commit.  They make
> the time functions do less redundant locking.
>
> However, in many places we do the following:
>
> 	pthread_mutex_lock();
> 	if (!is_set) {
> 		is_set = true;
> 		// do something
> 	}
> 	pthread_mutex_unlock();
>
> This is wasteful.  We get locks ALL the time for every time operation,
> when in fact we need it more rarely.  If we can tolerate losing a
> race, we can eliminate the locking in all but the startup case and
> those threads racing the startup:
>
> 	if (!is_set) {
> 		pthread_mutex_lock();
> 		if (!is_set) {
> 			is_set = true;
> 			// do something
> 		}
> 		pthread_mutex_unlock();
> 	}
>
> here, we know that is_set only ever changes from false to true.  If it
> is already true, there's nothing to do.  If it is false, we may need
> to do something, so we lock, check to see if we really need to do it,
> etc.
>
> Can anybody see a flaw in this logic?

Is this not a good place to use pthread_once() instead?

-- 
DE


More information about the freebsd-arch mailing list