What is wrong with this code? In addition to the line of code, why exactly is it
ID: 3743892 • Letter: W
Question
What is wrong with this code? In addition to the line of code, why exactly is it a problem? How would two threads incorrectly execute that line, down to the pseudo-assembly level?
#include <pthread.h>
#include <stdio.h>
void *dowork(void* arg) {
int x;
int* a = (int*)arg;
for(x = 0; x < 100000; x++) {
(*a)++;
}
pthread_exit(0);
}
void main(int argc, char** argv) {
int i;
pthread_t p[2];
int x;
i = 0;
for(x = 0; x < 2; x++) {
pthread_create(&p[x], NULL, dowork, &i);
}
for(x = 0; x < 2; x++) {
pthread_join(p[x], NULL);
}
printf("The final value of i is %d ", i);
pthread_exit(0);
}
Explanation / Answer
Problem with this code is both the threads trying to execute below code segment:
for(x = 0; x < 100000; x++) {
(*a)++;
}
When (*a)++ is converted to assembly code, it can be broken down to multiple assembly instructions which is:
Loading address of variable/instruction a is pointing to, then load value from that address and in the end increment the value by 1. If execution of one thread is interrupted by another thread in between these assembly instructions, this intoduces ambiguity in the code. Thus mutual exclusion must be implemented to avoid such race conditions.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.