Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

minimum and maximum value of a global variable with 2 thread

I have a for loop like
int c = 0 ;
for(int i=0 ; i<100 ; i++)
c++;

where C is a global variable.
if I run this code with 2 thread what is the minimum and maximum final value of C if I don't lock the threads in the section of c++ and how?

like image 433
Kibo Avatar asked Apr 17 '13 09:04

Kibo


1 Answers

if you translate increment code to assembly it's pseudocode will be like:

1-mov ax,mem[c]
2-inc ax
3-mov mem[c],ax

if we have 2 thread consider this scenario:

thread 1: line 1
thread 2: line (1-2-3) for 99 times
thread 1: line (2-3)
thread 2: line 1
thread 1: line (1-2-3) for remaining 99 times
thread 2: line (2-3) for the last time

now the value of c is 2 so minimum is 2

like image 106
Kibo Avatar answered Sep 30 '22 17:09

Kibo