Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Assume that the compiler performs no optimization and that all code runs on the

ID: 3734058 • Letter: A

Question

Assume that the compiler performs no optimization and that all code runs on the processor exactly as written. Also assume that no library calls will fail. #include 0001: 0002: #include 0003: #de fine NUM THREADS 4 0004: char array [NUM THREADS+21: 0005: int pos =0; 0006: char outs [9] # 0011 : 0012: 0013: 0014 char outs[index]: 0015 : 0016: return NULL 0017: 0018: int main() 0019: void * work (void* id) int index (* ( (int*) id)) *2; = array [pos++] = c; 0020: char three'z 0021: int i; 0022: pthread t tid [NUM THREADS] 0023 : for (i 0; í

Explanation / Answer

This program ideally should output length of the “array” i.e. when 4 threads modify the array they add 4 elements and ‘z’ is added by main function. So this should output 5 as length of array would be 5.

Race Condition: Since array[] is modified concurrently by these thread, they insert elements using index represented by ‘pos’ which is a shared variable. Line 15 will be broken down in machine language into many instructions s :

If a thread gets interrupted by another thread in between these instructions, say after assigning c to array, then pos will not be incremented and next thread might also end up inserting element at pos location. In that case instead of 2 only 1 element gets inserted in the array and length of array reported in main will be lesser than expected.

Solution: Use mutex. All the code inside function work() should be wrapped inside mutex as below:

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void * work(void* id){

            pthread_mutex_lock(&mutex);

            int index = (*((int*)id))*2;

            char c = outs[index];

            array[pos++] = c;

            return NULL;

            pthread_mutex_unlock(&mutex);

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote