Zagatho
Zagatho

Reputation: 523

strange behaviour with threads in for loop

We have to implement a multithreading bucket sorting algorithm in C. I have simplified the code, which has the same problem.

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

int max_threads;

void *bucket_sort( void * );


int main( int argc, char *argv[] )
{
    srand( time( NULL ) );
    if( argc != 2 )
    {
        printf( "Wrong arguements\n" );
        exit( EXIT_FAILURE );
    }

    max_threads = ( int ) strtol( argv[1], NULL, 10 );
    pthread_t *threads = malloc( sizeof( pthread_t ) * max_threads );

    for( int i = 0; i < max_threads; )
    {

        if( pthread_create( &threads[i], NULL, bucket_sort, &i ) )
            exit( EXIT_FAILURE );
        i++;
    }

    for( int i = 0; i < max_threads; ++i )
        pthread_join( threads[i], NULL );
}


void *bucket_sort( void *param )
{
    int p = *( int * )param;
    printf( "%d\n",p );
}

If i run the program with ./a.out 10, the output shoult be something like this:

0 1 2 3 4 5 6 7 8 9

I know it is possible that the order of the output may vary, but all elements from [0,9] should be printed exactly once. But the output is completely different:

1234334445

7676543543

Thats not the output i have expected. Why is the output of my program so strange? What can I do, to get the behaviour which I expect?

Thanks Patrik

Upvotes: 0

Views: 49

Answers (1)

Alex F
Alex F

Reputation: 43311

Make the following change:

if( pthread_create( &threads[i], NULL, bucket_sort, (void*)i ) )

...

int p = (int)param;

Your code passes pointer to i, the variable changes meanwhile, finally it goes out of scope, this is undefined behavior. Pass i value instead of the pointer.

Upvotes: 2

Related Questions