I have written a program for creating number of threads. The number can be passed as a command line argument or default value is 5. The problem I am facing is printing the thread number passed as an argument to pthread writer function.
Below is my program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
void *writerThread(void *args)
{
int id = *((int *)args);
printf("In thread %d\n", id);
}
int main(int argc, char *argv[])
{
int numThreads;
if(argc != 2)
numThreads = 5;
else
numThreads = atoi(argv[1]);
pthread_t *tId = (pthread_t*) malloc(sizeof(pthread_t) * numThreads);
int i;
for(i = 0; i < numThreads; i++)
{
pthread_create(&tId[i], NULL , writerThread, &i);
}
// wait for threads
for(i = 0; i < numThreads; i++)
pthread_join(tId[i], NULL);
if(tId)
free(tId);
return 0;
}
Output:
In thread 2
In thread 0
In thread 3
In thread 2
In thread 0
Why 0 and 2 are coming two times ? Any help would be appreciated.