Spinlock implementation

Hi.

I’m reading the nginx spinlock implementation, since I would like to use
it in a separate project I’m working on.

The code is quite simple, however there is a thing I’m not sure to
unserstand:
why ngx_cpu_pause is called only if Nginx detects that more than 1
cpu are in use?
Moreover the number of CPU is only detected for Free BSD.

Thanks Manlio P.

On Sat, Aug 16, 2008 at 02:09:58PM +0200, Manlio P. wrote:

I’m reading the nginx spinlock implementation, since I would like to use
it in a separate project I’m working on.

The code is quite simple, however there is a thing I’m not sure to
unserstand:
why ngx_cpu_pause is called only if Nginx detects that more than 1
cpu are in use?

If nginx detects more than 1 CPU, then it tries to acquire lock in short
loop. If system has the single CPU then the loop is useless: another
process/thead holding the lock does not run at the moment and will not
release the lock in nearest future.

ngx_cpu_pause is P4 hyperthreading optmization for such loops.

The spinlock is optimized to run on SMP systems. For example,

    if (*lock == 0 && ngx_atomic_cmp_set(lock, 0, value)) {
        return;
    }

is better than simple:

    if (ngx_atomic_cmp_set(lock, 0, value)) {
        return;
    }

Moreover the number of CPU is only detected for Free BSD.

Yes, this bug should be fixed.

Igor S. ha scritto:

If nginx detects more than 1 CPU, then it tries to acquire lock in short
loop. If system has the single CPU then the loop is useless: another
process/thead holding the lock does not run at the moment and will not
release the lock in nearest future.

What about a single CPU with hyperthreading enabled?

ngx_cpu_pause is P4 hyperthreading optmization for such loops.

Ok.

    }

Moreover the number of CPU is only detected for Free BSD.

Yes, this bug should be fixed.

Thanks Manlio P.

On Sat, Aug 16, 2008 at 09:36:21PM +0200, Manlio P. wrote:

If nginx detects more than 1 CPU, then it tries to acquire lock in short
loop. If system has the single CPU then the loop is useless: another
process/thead holding the lock does not run at the moment and will not
release the lock in nearest future.

What about a single CPU with hyperthreading enabled?

This is SMP case, i.e. ngx_cpu > 1.