user12248063
user12248063

Reputation:

How to create a variable number of pthreads?

A part of a programming assignment I have at college specifies:

for the threads, initialize a large array of pthread_t* in main() and dynamically create pthread_t for each new student using malloc(sizeof(pthread_t).

Seems simple enough. All I would have to do is something like:

pthread_t *pthreadArray = malloc(sizeof(pthread_t) * userInputSize);

to create a variable number of threads. However, we are not given a userInputSize. How is this possible then? If I were to just do:

pthread_t *pthreadArray = malloc(sizeof(pthread_t));  

wouldn't that only give me a single pthread to work with? I feel as though this must be an issue in the programming instructions. Any ideas?

Upvotes: 2

Views: 1050

Answers (1)

HAL9000
HAL9000

Reputation: 2188

So just do as the assignment says:

for the threads, initialize a large array of pthread_t* in main()

/* Large number */
const size_t max_threads = 100;

/* Large array of pointers with every element initialized to zero */ 
pthread_t *student_threads[max_threads] = {};

size_t thread_count = 0;

and dynamically create pthread_t for each new student using malloc(sizeof(pthread_t))

pthread_t *new_student = malloc(sizeof(pthread_t));

What is not written is what you do with new_student. It is indeed a pointer to a single pthread_t. Just put the pointer in the next unused slot in your array:

/* Find next unused spot in array (with value==NULL) */
size_t i = 0
while (i < max_threads && student_threads[i])
   i++;

/* assign value to that spot */
student_threads[i] = new_student;
thread_count++;

Remember to add error checking where appropriate. And release all resources when you are finished with them.

That includes setting student_threads[i]=NULL whenever you call free(student_threads[i]) so you know which slots in array are unused.

Upvotes: 2

Related Questions