Re: volatile and threading
On Jan 22, 2:46 am, Kira Yamato wrote:
On 2008-01-21 20:09:49 -0500, Agras <sk...@klania.me> said:
I have a shared variable between threads:
volatile int a;
Inside threads, `a` will be increased (a++) and decreased (a--) many
times without mutexes.
I believe this is correct, because a++ and a-- needs only one assembly
instruction.
Am I right, or mutexes are needed?
Hmm... I can't seem to see why a standalone statement
a++;
or
++a;
would need mutex protection since you are not reading its value while
changing it.
If you only do it in one thread, mutexes aren't needed.
Otherwise: as more than one thread accesses a variable, and any
thread might modify it, some form of synchronization is needed.
(On most processors, it's possible to write an atomic increment
without using mutexes. But you'll likely need some special
hardware instructions to do so, instructions which are never
generated by the compiler.)
--
James Kanze (GABI Software) mailto:james.kanze@gmail.com
Conseils en informatique orient=EF=BF=BDe objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=EF=BF=BDmard, 78210 St.-Cyr-l'=EF=BF=BDcole, France, +33 (0)1 30 2=
3 00 34