Basically, I create an array with 10 elements inside main and create two threads. The first thread, calcOddIndex, will calculate the product of all elements with odd index inside the array. The second thread, calcEvenIndex, will calculate the product of all elements with even index inside the array. Main will finally output the results after two child threads finish.
It gives me the error below. I think I am not passing the array correctly to the pthread_create. How should I fix this?
Here is my code:
It gives me the error below. I think I am not passing the array correctly to the pthread_create. How should I fix this?
Here is my code:
Code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
/* first thread will calculate the product of all elements with odd index inside the array */
void *calcOddIndex(int arr[10]);
int oddIndexProduct = 1;
/* the second thread will calculate the product of all elements with even index inside the array */
void *calcEvenIndex(int arr[10]);
int evenIndexProduct = 1;
int main() {
pthread_t tidOdd; /* the thread identifier for calcOddIndex */
pthread_t tidEven; /* the thread identifier for calcEvenIndex */
pthread_attr_t attr; /* set of thread attributes */
/* create an array with at least 10 elements */
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
/* get the default attributes */
pthread_attr_init(&attr);
/* create thread for calcOddIndex */
pthread_create(&tidOdd, &attr, calcOddIndex, &array);
/* create thread for calcEvenIndex */
pthread_create(&tidEven, &attr, calcEvenIndex, &array);
/* wait until both threads is done with their work */
pthread_join(tidOdd, NULL);
pthread_join(tidEven, NULL);
// print the product of all elements with odd index
printf("product of odd index inside the array = %d\n", oddIndexProduct);
// print the product of all elements with even index
printf("product of even index inside the array = %d\n", evenIndexProduct);
} // end of main
/*
calculate the product of all elements with odd index inside the array
*/
void *calcOddIndex(int arr[10]) {
for (int i=1; i<10; i=i+2) {
oddIndexProduct *= arr[i];
}
pthread_exit(0);
} // end of calcOddIndex
/*
calculate the product of all elements with even index inside the array
*/
void *calcEvenIndex(int arr[10]) {
for (int i=0; i<10; i=i+2) {
evenIndexProduct *= arr[i];
}
pthread_exit(0);
} // end of calcEvenIndex