Friday 2 December 2011

Question about pthreads

Question about pthreads

Hi guys

I have a question about thread programming. Based on the material on the web, I created a simple program that would create a bunch of threads in a loop like this:

#define N_THREADS 5
void* thread_function(void*);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;

int main()
{
int i;
int j;
int i_ptr=&i;
pthread_t threads[N_THREADS];

for(i=0; i < N_THREADS; i++)
{pthread_create( &threads[i], NULL, thread_function, (void*) i_ptr);
//sleep (1);}

for(j=0; j < N_THREADS; j++) pthread_join( threads[j], NULL);

return (0);
}

void* thread_function(void* data)
{
pthread_mutex_lock( &mutex1 );
int thread_data=*(int*)data;
counter++;
printf("I am thread number %d Counter value is %d\n",thread_data, counter);
pthread_mutex_unlock( &mutex1 );
pthread_exit("NULL");
}


When I execute the code above, I should normally get:

I am thread number 0 Counter value is 1
I am thread number 1 Counter value is 2
I am thread number 2 Counter value is 3
I am thread number 3 Counter value is 4
I am thread number 4 Counter value is 5

But instead i get:

I am thread number 1 Counter value is 1
I am thread number 5 Counter value is 2
I am thread number 5 Counter value is 3
I am thread number 5 Counter value is 4
I am thread number 5 Counter value is 5

or

I am thread number 1 Counter value is 1
I am thread number 5 Counter value is 3
I am thread number 2 Counter value is 2
I am thread number 5 Counter value is 4
I am thread number 5 Counter value is 5


or even(!):

I am thread number 5 Counter value is 1
I am thread number 5 Counter value is 2
I am thread number 5 Counter value is 3
I am thread number 5 Counter value is 4
I am thread number 5 Counter value is 5



Counter values seem to be fine, but why is the thread numbers not working properly? When i debug it with gdb, it works fine. When I add the sleep in the first loop, i also get correct output.
What could be the reason for this weird behavior?:shock:

No comments:

Post a Comment