Valiant Valemore
Valiant Valemore

Reputation: 69

how do I declare a global array of pthreads without knowing the size beforehand?

The user is supposed to give the number of threads to be created as argument.

That being said, I need to store them in an array, but such array needs to be global.

How can I declare the list, when I don't know the size beforehand? I mean, the integer nthreads is only initialized in the MAIN function. Here's a sample, so you understand better what I'm trying to do:

int nthreads;
pthread_t thread_array[nthreads];
int main(int argc, char** argv){
   nthreads = atoi(argv[0]);
}

Upvotes: 0

Views: 672

Answers (1)

Sergey L.
Sergey L.

Reputation: 22552

Declare a pointer and allocate enough memory at runtime.

int nthreads;
pthread_t * thread_array;
int main(int argc, char** argv){
    nthreads = atoi(argv[0]);
    thread_array = calloc(sizeof(*thread_array), nthreads);

    int i;
    for (i = 0; i < nthreads; i++) {
        pthread_start(thread_array + i, NULL, my_thread_function, my_thread_argument);
    }

    for (i = 0; i < nthreads; i++) {
        pthread_join(thread_array[i], NULL);
    }
}

Upvotes: 1

Related Questions