On Wed, Nov 03, 2004, Dvir Volk wrote about "Re: Why not using global variables 
considered thread-safe ?":
> On a 1-CPU machine, when you have global variables such as ints or 
> floats, isn't reading and writing them atomic, and needs no locking?
> what are the general rules this issue?

This is a complicated issue, and depends on the details of the CPU (i.e.,
different in different CPUs) and how it implements different C instructions
that you consider "reading and writing".

For example, what happens when you do "var += 3"? Is this "reading and
writing" and therefore don't need locking? Of course not:

A certain CPU's assembly
language might look something like

        load var    /* load var into register */
        add 3       /* add 3 to the register */
        store var   /* store back into var */

A context switch, even on a one CPU machine, might occur in the middle of this
process, e.g., just before the "store var", and cause a modification of the
same var in a different thread to be lost when we return to this thread and
finally do this "store var".

C Instructions which happen to be one machine instruction on your CPU, e.g.,
"var++" or "var=3", *are* guaranteed to be ok on a one-CPU machine. But even
those things are *not* guaranteed to be ok on an SMP (multi-CPU) machine.
Linux has an include file, "atomic.h", which guarantees various atomic
operations which will work correctly even on SMP machines.

-- 
Nadav Har'El                        |   Wednesday, Nov 3 2004, 19 Heshvan 5765
[EMAIL PROTECTED]             |-----------------------------------------
Phone +972-523-790466, ICQ 13349191 |"Arguing with nyh just doesn't pay off."
http://nadav.harel.org.il           |-- Muli Ben-Yehuda, Linux-il list

=================================================================
To unsubscribe, send mail to [EMAIL PROTECTED] with
the word "unsubscribe" in the message body, e.g., run the command
echo unsubscribe | mail [EMAIL PROTECTED]

Reply via email to