0
votes

I'm working in C, and I'm trying to pass in a pointer to an array that will hold my thread ids, but I cannot seem to get my types to match. What am I not understanding about passing pointers in C?

This is my function:

int createThreads(int numThreads, pthread_t **tidarray) {

    pthread_t *tids = *tidarray;

    int i;
    for (i = 0; i < numThreads; i++) {
        pthread_create(tids + i, NULL, someFunction, NULL);
    }

    return 0;
}

And this is my call:

pthread_t tids[numThreads];

createThreads(5, &tids);

When I compile this, I get a warning: Passing argument 2 of 'createThreads' from incompatible pointer type, and Note: expected 'pthread_t **' but argument is of type 'pthread_t (*) [(long unsigned int)(numThreads)]'

2
It looks like you want the argument to be a pthread_t *, not a **. - user253751
tidarray is not an array pointer, it's a pointer to a pointer. An array pointer would be pthread_t (*tidarray)[numThreads], as suggested by the error message. - emlai

2 Answers

0
votes
#include <stdio.h>
#include <pthread.h>


// dummy function for threads , it just print its argument
void * someFunction(void *data){

    printf("Thread %d\n",(int)data);
}


int createThreads(int numThreads, pthread_t *tidarray) {
    int i;
    for (i = 0; i < numThreads; i++) {
        //pass the pointer of the first element + the offset i
        pthread_create(tidarray+i, NULL, someFunction, (void*)i);
    }

    return 0;
}

int main(){
    pthread_t tids[5]={0};// initialize all to zero 
    createThreads(5, tids);
    getchar();// give time to threads to do their job

    // proof-of-concept, the array has been filled by threads ID
    for(int i=0;i<5;i++)
        printf("Thread (%d) ID = %u\n",i,tids[i]);
    return 0;
}
-1
votes

You don't need the & address of operator, just pass it as it is because it's converted to a pointer automatically, so

createThreads(5, tids);

is what you need, and then your createThreads() function

int createThreads(int numThreads, pthread_t *tids) 
{    
    int i;
    for (i = 0; i < numThreads; i++) 
    {
        pthread_create(tids + i, NULL, someFunction, NULL);
    }    
    return 0;
}