Carlos Pereira
Carlos Pereira

Reputation: 391

Calculate the sum of two numbers using thread

I have this little program I wrote to read two numbers from a user and calculate their sum using a thread function, which is also responsible for displaying the result on the screen.

int global[2];

void *sum_thread(void *arg)
{
    int *args_array;
    args_array = *(int**)arg;

    int n1,n2,sum;
    n1=args_array[0];
    n2=args_array[1];
    sum = n1+n2;

    printf("N1 + N2 = %d\n",sum);

    return NULL;
}

int main() 
{
    printf("First number: ");
    scanf("%d",&global[0]);

    printf("Second number: ");
    scanf("%d",&global[1]);

    pthread_t tid_sum;
    pthread_create(&tid_sum,NULL,sum_thread,(void*)&global);
    pthread_join(tid_sum,NULL);

    return 0;
}

However, when I run the code, it does not work properly due to a segmentation fault. I suppose I am trying to access/use unallocated memory. Should I allocate it with malloc or is there other things I am doing wrong?

Upvotes: 1

Views: 13728

Answers (2)

John Bollinger
John Bollinger

Reputation: 180306

You pass (void*)&global as the thread start function's argument. The type of &global is (*)int[2] -- pointer to array of two int. That is different from and incompatible with int **, which is a pointer to a pointer to int. Arrays are not pointers.

@SouravGhosh already offered a solution that gets the typing correct, and should work just fine. I observe, however, that in this particular case it's a bit silly to pass a pointer to the global array, because the thread could instead just read the array directly:

void *sum_thread(void *arg)
{
    int n1,n2,sum;
    n1=global[0];
    n2=global[1];
    sum = n1+n2;

    printf("N1 + N2 = %d\n",sum);

    return NULL;
}

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

The name of the array, global points to the base address of the array. You can simply pass that and use the same inside your thread function.

However, just to mention a logical point, if you're passing global as a parameter to sum_thread() function, it need not be a global.

In your code, change

pthread_create(&tid_sum,NULL,sum_thread,(void*)&global);

to

pthread_create(&tid_sum,NULL,sum_thread,global);

Then, in sum_thread() function

args_array = *(int**)arg;

to

args_array = arg;

Upvotes: 2

Related Questions