Re: [linux-usb-devel] Re: [PATCH 00/10] usb-serial: Switches fromspin lock to atomic_t.

From: Alan Stern
Date: Wed Dec 07 2005 - 11:07:59 EST


On Wed, 7 Dec 2005, linux-os (Dick Johnson) wrote:

> You need to know what it is that you intend to do if the code
> encounters a locked section.
>
> For example, let's pretend that every operation is atomic so
> that only the logic is investigated...
>
> if(!critical_section_flag) {
> critical_section_flag = TRUE;
> do_something_in_critical_section();
> }
> else
> WTF?;
>
>
> A spin-lock will prevent the current CPU from even getting to
> or modifying data in the critical section because alternate paths
> via interrupts are blocked. The only other way for data to be
> modified is from another CPU. That CPU will spin until the current
> CPU releases the lock.
>
> Atomic operations on flags (semaphores) provide the opportunity
> for another CPU to do something useful until the critical section
> is released, the WTF above. However, if the other CPU can't
> schedule you are caught between a rock and a hard-place because
> you would need to spin anyway.
>
> Basically, if you can schedule, it's much better to protect
> a section with semaphores and do the down(&semi) / up(&semi) thing.
> If you can't schedule, it's much cleaner to use a spin-lock
> which, in fact, will prevent interference with the critical
> section in most cases because, unless another CPU is idle,
> it is unlikely to encounter the same thread of code.

That's true as far as it goes. But it ignores the possibility that, for
example, the critical section is extremely short (like incrementing an
integer variable). In such situations, spinning is better than
scheduling. And even better than spinning is for the CPU to wait while
another CPU carries out a locked bus cycle (which is what atomic_t
operations do on x86). As well as being more efficient, it may even be
"cleaner" -- depending on one's personal taste. :-)

Alan Stern

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/