Re: [PATCH] Fix a race in pid generation that causes pids to be reused immediately.

Linus Torvalds
2010-06-09T21:22:09Z

On Wed, 9 Jun 2010, Salman wrote:
> +/*
> + * If we started walking pids at 'base', is 'a' seen before 'b'?
> + *
> + */
> +static int pid_before(int base, int a, int b)
> +{
> + int a_lt_b = (a < b);
> + int min_a_b = min(a, b);
> + int max_a_b = max(a, b);
> +
> + if ((base <= min_a_b) || (base >= max_a_b))
> + return a_lt_b;
> +
> + return !a_lt_b;
> +}

Ok, so that's a very confusing expression. I'm sure it gets the right
value, but it's not exactly straightforward, is it?

Wouldn't it be nicer to write it out in a more straightforward way?
Something like

/* a and b in order? base must not be between them */
if (a <= b)
return (base <= a || base >= b);
/* b < a? We reach 'a' first iff base is between them */
return base >= b && base <= a;

would seem to be equivalent and easier to explain, no?

And when you write it that way, it looks like the compiler should be able
to trivially CSE the five comparisons down to just three (notice how the
"base <= a" and "base >= b" comparisons are repeated. Which I'm sure some
super-optimizing compiler can do from your version too, but mine seems
more straightforward.

But maybe I did that thing wrong, and I just confused myself. I have _not_
checked the logic deeply, somebody else should definitely double-check me.

Linus