Here's one thing I don't understand. Let's say two threads are going through an iterative loop. Thread A has the code:
for( int i = 0; i < 10; i++ ){
str1[i] = fgetc( stdin );
}
while Thread B has the code:
for( int j = 0; j < 10; j++ ){
str2[j] = fgetc( stdin );
}
Let's say that i and j occupy the same memory location (I know this is highly unlikely, but this is just an example).
Since each thread contains an I/O instruction, the threads will stop execution as they wait for input, resulting in a context switch. Both A and B will thus increment the memory location until the value is 10. The number of iterations for A and B add up to 10, but neither one of them goes through all the iterations. For instance, the value of j could be 4. A context switch occurs between B and A, and A increments it to 5, and when the context switch occurs again, B has the value 5 instead of 4. Thus 4 is skipped.
So basically my question is, if two threads modify the same memory location, and both of them depend on it being a certain value that may have been altered by the other thread (a possible cause of a deadlock), what is used to prevent this?


Sign In
Create Account


Back to top









