cpthreads

Shared data access in pthreads


My questions are : How many values ​​can the output of the following code take? What are these values? What is the reason for different values? How can we prevent different values ​​from occurring?

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>

int shared_data = 100;


void* thread_function(void *args)
{
    long temp;
    long *j = (long *) args;
    temp = shared_data;
    temp = temp + &j;
    shared_data = temp;
    
    return (NULL);
}



int main() 
{

long i = 0;
long tinfo[] = {1,2,3};
pthread_t ids[3];

for(int i=0 ;i<3;i++)
{
    pthread_create(ids+i,NULL,&thread_function, &tinfo[i]);
}

for(int i=0 ;i<3;i++)
{
    pthread_join(ids[i],NULL);
}

printf("shared data = %d\n",shared_data);

}

I was working on system programming and operating system and saw this exercise. I have tried to make a research but the topic is very new to me. It is not an homework or exam question, It is one of the past interview question of an institution.


Solution

  • Assuming an answer is expected rather then a correction to the many flaws which are likely unintentional, in answering this question, you would do well to state some assumptions to deal with the "undefined" behaviour of the poorly formed code. Doing so would demonstrate your knowledge of such issues should the question in fact be intended to be about that, but it also allows you to answer the question in the manner the institution probably intended. They ,may even fix the question for next candidate! Unfortunately the world is full of such flawed interview questions - if you want to gain entry to the course, you need to play the game. But you may not want to enrol if this is indicative of the quality of their teaching perhaps.

    Anyhow, if we state:

    Assumptions:

    Then the output variability will depend on the order in which each thread starts - which need not be the order in which they were created. As such it is a question of permutations of 1,2,3 which is 3 x 2 x 1 = 6. So the answer then is a matter of performing the thread function calculation for each to the six possible permutation of execution order.

    Without the assumptions the result is entirely undefined.

    Given those assumptions the "fix" is not to use threads at all, but to call the function sequentially in a single fixed order. No doubt there are more complicated solutions using thread synchronisation, but there is no practical benefit of run to completion threads in a defined sequential order.