0

I just started to get into threads in POSIX C, and I am confused how to create global array pthread_t t[NUM_OF_THREADS] where NUM_OF_THREADS should be determined at run time. I need to create a separate thread for each category my program receives, and it can be any number of categories.

So, I do not know how many threads I should create. Basically I am calculating the number of categories in my code, and I want to create the same number of threads in my program. How would I do that?

I cannot create a global array with some variable number for NUM_OF_THREADS, meaning that NUM_OF_THREADS should be constant. I also need this array of threads to be accessible from different functions. I am stuck.

How do you work with threads if you do not know their number before runtime?

Thank you

twasbrillig
  • 17,084
  • 9
  • 43
  • 67
YohanRoth
  • 3,153
  • 4
  • 31
  • 58
  • 4
    Just don't store your `pthread_t`s into a fixed-size global array. Is the question asking for an answer more complicated than that? – Tommy Nov 17 '14 at 04:56
  • Just like you work with any other data type without knowing its number before run time. – n. m. could be an AI Nov 17 '14 at 04:56
  • @Tommy But global data is what being shared between threads... and I need this data to be global and accessible from any part of my source code.. I am confused – YohanRoth Nov 17 '14 at 05:04
  • Well, design your global data so that it doesn't need an array of the threads. It's far from unusual to not bother keeping any record of the 'pthread_t's at all and to communicate with the threads in some other fashion. – Martin James Nov 17 '14 at 05:32

2 Answers2

2

You question doesn't seem to have as much to do with threading as it does a global variable. You need a pointer...

#include <stdlib.h>
#include <pthread.h>

const size_t NUM_OF_THREADS = 5;
pthread_t *my_threads = NULL;

int spawnThreads (void);

int main (void) {
   // can access my_threads;
   my_threads = malloc(sizeof(pthread_t *) * NUM_OF_THREADS);
   otherFunc();
   free(my_threads);
   return 0;
}

int spawnThreads (void) {
    // can access my_threads;
    for (int i = 0 ; i < NUM_OF_THREADS ; ++i ) {
        my_threads[i] = pthread_create(...);
    }
    return 0;
}
Zak
  • 12,213
  • 21
  • 59
  • 105
0

the question is same as how to use a array if you don't know the lenth before runtime.

a direct way is to use variable-length arrays, there's something matters as an answer says

variable-length arrays in C are a fairly dangerous construct, because they perform dynamic allocation on the stack. They're basically alloca() in disguise, and we know how dangerous alloca() is.

a more safe way is to malloc a block of memory at first. while i'm editing the answer, @Zak shows a example, that's a good way. Just regard my answer as an addtion ;)

Community
  • 1
  • 1
simon_xia
  • 2,394
  • 1
  • 20
  • 32