Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically allocate(initialize) a pthread array?

Tags:

c

pthreads

I have a pthread pointer, and I need to allocate enough space for the pointer to hold enough number of pthread. Then initialize them and pthread_create() to pass thread to some functions.

The problem is that if I just use malloc to allocate space to the pointer, then just pthread_create using pointer[index], then the thread will not be created properly. How do I fix this problem? I believe pthread_t is some type of struct, so I believe I need to initialize them before I do pthread. how do I do that? thank you.

I just tested with certain amount of pthread that they worked properly:

pthread_t t1, t2, t3 ...... tn;

then

pthread_create(&t1, NULL, function, (void *)argument)

But if I use pointer and malloc, they wont work.Thread will not be created.

pthread_t *ptr;

ptr = malloc(sizeof(pthread_t)*num);

then

pthread_create(&ptr[index], NULL, function, (void *)argument)

will not work. How do I initialize then ptr[index] in this case?

like image 358
Kko Avatar asked Sep 18 '25 12:09

Kko


1 Answers

yes, it should work. what is your some space?

You did not put complete code, but just a suggestion, did you initialize num ?

Check the below code. I believe it's working.

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void* func(void* id)
{
        int *c;
        c = (int*)id;
        if(c)
                printf("%d\n", *c);
}

int main(int argc, char *argv[])
{
        int i = 0;
        int *index = NULL;
        int num;
        pthread_t *ptr;
        if (argv[1])
                num = atoi(argv[1]);

        index = calloc (num, sizeof (int));
        for(i = 0; i < num; i++)
        {
                index[i] = i;
        }

        ptr = malloc(sizeof(pthread_t)*num);
        for(i = 0; i < num; i++)
        {
                pthread_create(&ptr[i], NULL, func, (void*)&index[i]);
        }
        for(i = 0; i < num; i++)
                pthread_join(ptr[i], NULL);

        return 0;
}
like image 58
Sourav Ghosh Avatar answered Sep 21 '25 03:09

Sourav Ghosh