How to fix no matching function for call to 'pthread_create' in multithreading?

Thread Starter

asilvester635

Joined Jan 26, 2017
73
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?
chegg.png

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
 

xox

Joined Sep 8, 2017
598
The callback function you're passing to pthread_create has the wrong prototype ("signature"). It has to be declared like this:

Code:
void* calcOddIndex(void* data);
Inside the function you cast the void* parameter "data" back to the correct type. In other words:

Code:
void* calcOddIndex(void* data){
    int* arr = (int*)data;
    for (int i=1; i<10; i=i+2) {
        oddIndexProduct *= arr[i];
    }
    pthread_exit(0);
} // end of calcOddIndex
 
Last edited:
Top