Hello,
Please see my code below, where I invoke 100 threads. I have the following questions. Please see the log file attached when referring to the below questions.
1. Why are my threads largely in serial order? I find it to be mostly in ascending order from 0-99. Shouldn't the order of threads be not able to predict?
2. Some threads like 68 etc are executed many times. The only reason I can think of is it's getting thrown out by another thread and then coming back to print again. But I do have a mutex lock - mutex unlock inside the function which prints the thread id.
3. Why don't I see all numbers between 0-99? Thread ids from 71 onward are missing and possibly some more in between 0 and 71.
Code:
#include <stdio.h>
#include <pthread.h>
void* fun(void*);
pthread_mutex_t lock;
int counter = 0;
int main(void)
{
int ret = 0;
pthread_t th[100];
int i = 0;
pthread_mutex_init(&lock, NULL);
for(i=0;i<100;i++)
{
pthread_create(&th[i], NULL, fun, &i);
}
//sleep
for(i=0;i<100;i++)
pthread_join(th[i],NULL);
pthread_mutex_destroy(&lock);
return 0;
}
void* fun(void* arg)
{
int i = 0;
pthread_mutex_lock(&lock);
int* ptr = (int*)arg;
/* I get threads in serial order even upon un-commenting this for loop */
/*for(i=0;i<0xFFFFFFFF;i++)
{
}*/
printf("ThreadID : [%d]\n",*ptr);
pthread_mutex_unlock(&lock);
//return NULL;
}
Please advise
Thanks.
Bookmarks