In: Computer Science
Explain the errors in the C code that cause the output NOT to be -10. (Hint: There are 2 errors):
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define SIZE 5
void *threadFunc(void *arg);
int *changingVal;
int a[SIZE]; // Assume a[] = { 13444, 3320, 31020, 3302, 31313
};
int main() {
int i;
int min;
int * changeVal = malloc (sizeof(int*));
*changeVal = -10;
// Thread creation
pthread_t thread1;
pthread_attr_t attr;
pthread_attr_init(&attr);
for (i = 0; i < SIZE; i++) {
a[i] = rand();
printf("%d\n", a[i]);
}
min = a[0];
pthread_create(&thread1,&attr,threadFunc,
&changeVal);
#pragma omp parallel for num_threads(1)
for (i = 1; i < SIZE; i++) {
if (a[i] < min) {
pthread_join(thread1, NULL);
#pragma omp critical
{
// compare a[i] and min again because min
// could have been changed by another thread after
// the comparison outside the critical section
if (a[i] < min)
min = a[i];
}
}
}
printf("Min number found:\t%d\n", min);
}
void * threadFunc(void *arg) {
changingVal = (int*) arg;
a[3] = *changingVal;
pthread_exit(0);
}
Updated Code is in BOLD!!
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define SIZE 5
void *threadFunc(void *arg);
int *changingVal;
int a[SIZE]; // Assume a[] = { 13444, 3320, 31020, 3302, 31313
};
int main() {
int i;
int min;
int * changeVal = malloc (sizeof(int*));
*changeVal = -10;
// Thread creation
pthread_t thread1;
pthread_attr_t attr;
pthread_attr_init(&attr);
for (i = 0; i < SIZE; i++) {
a[i] = rand();
//printf("%d\n", a[i]); We
need not to print here, instead print after updation
}
min = a[0];
//pthread_create(&thread1,&attr,threadFunc,
&changeVal); , This was error
pthread_create(&thread1,&attr,threadFunc,
changeVal);
for (i = 0; i < SIZE; i++)
{
printf("%d\n",a[i]);
}
#pragma omp parallel for
num_threads(1)
for (i = 1; i < SIZE; i++) {
if (a[i] < min) {
pthread_join(thread1, NULL);
#pragma omp critical
{
// compare a[i] and min again because min
// could have been changed by another thread after
// the comparison outside the critical section
if (a[i] < min)
min = a[i];
}
}
}
printf("Min number found:\t%d\n", min);
}
void * threadFunc(void *arg) {
changingVal = (int*) arg;
a[3] = *changingVal;
pthread_exit(0);
}
The first error was that we are passing the reference of the changeVal -
pthread_create(&thread1,&attr,threadFunc, &changeVal);
Instead, we need to pass the value of changeVal ,i.e, -10
pthread_create(&thread1,&attr,threadFunc, changeVal);
The second error was we are printing the value of "a" before the updation
for (i = 0; i < SIZE; i++) {
a[i] = rand();
//printf("%d\n", a[i]); Comment this to avoid this line to
run!!
}
pthread_create(&thread1,&attr,threadFunc, changeVal);
Instead we will print after updation
pthread_create(&thread1,&attr,threadFunc, changeVal);
for (i = 0; i < SIZE; i++)
{
printf("%d\n",a[i]);
}