-2

I am trying to create dynamic number of thread.....

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

void* thread_function(void)
{
    printf("hello");
}
int main(int argc,char *argv[])
{
    int noOfThread= atoi(argv[1]);
    pthread_t thread_id[noOfThread];
    int i;
    int status;
    for(i=0;i<noOfThread;i++)
    {
        pthread_create (&thread_id[i], NULL , &thread_function, NULL);
    }  

    for(i=0;i<noOfThread;i++)
        pthread_join(thread_id[i],NULL);   
}

3 errors:

  1. implicit declaration of function atoi....
  2. passing arguement 3 of 'pthread_create' from incompatible pointer type
  3. expected 'void * (*)(void *)' but arguement is of typr'void * (*) (void)'......
melpomene
  • 84,125
  • 8
  • 85
  • 148
ycsjose
  • 27
  • 7

1 Answers1

2

There are several issues here:

  1. You need to include stdlib.h for the declaration of atoi()
  2. A pthread task function has a void* argument. This will fix issue #2 and #3. (http://man7.org/linux/man-pages/man3/pthread_create.3.html).

    void* thread_function(void* arg);
    
  3. To be most portable and compliant with older C compilers, you should allocate your pthread_t array using malloc explicitly. Make sure to check for a NULL return value and free the memory later in this case. Or you can declare a maximum number of threads to allocate and use a constant array size.

    pthread_t* thread_id = malloc(noOfThread*sizeof(pthread_t));
    
Paul
  • 370
  • 1
  • 6