Question : Integers and Thread Safety

Is it thread safe to increment an integer and then read from it? My concern is that two threads would increment an int at the same time and then read the same value from it. Is that a possibility or is incrementing integers completely thread safe?

Thanks,
Dan

Answer : Integers and Thread Safety

I don't think it is safe. Because i++ would really mean something like

In INTEL:
   movl i, AX
   inc AX

In AMD:
   movl    $0, -4(%rbp)
   addl    $1, -4(%rbp)


So, in effect, it is two assembly instructions, and if the context switch happens in between, then the data is corrupted
Random Solutions  
 
programming4us programming4us