c++ - Using threads to sort two halves of an array, but only second half is being sorted -



c++ - Using threads to sort two halves of an array, but only second half is being sorted -

i wrote quick programme sort 2 halves of 1 array, when test sort works fine 1 array, when split array 2 , pass half each thread sorting, when they're done , print array, sec half looks sorted. doing wrong? below sorting function , main.

void *sort(void *object){ struct array_struct *structure; construction = (struct array_struct *) object; int *array = structure->partition; int size = structure->size; qsort(array, size, sizeof(int), cmpfunc); printf("sorted %d elements.\n", size); }

and main, assume includes fine, , compilation fine also, not of code, parts pertaining problem.

int main(int argc, char const *argv[]){ int segments = 2; pthread_t threads[segments]; int i, *numbers; //iterator i, , pointer int array 'numbers' numbers = randomarray(); //return array of size 50 filled random ints for(i = 0; < segments; i++){ struct array_struct array;//struct pass argument on thread creation int *partition = numbers + (i * (50/segments));//obtain first index of partition array.partition = partition; //when = 0 partition 0 through 24, when = 1 partition 25 through 49 array.size = 50/segments; //25 pthread_create(&threads[i], null, sort, (void *) &array); } for(i = 0; < segments; i++){ pthread_join(threads[i], null); } for(i = 0; < 50; i++){ printf("%d\n", numbers[i]); } pthread_exit(null); }

and here output if helps:

sorted 25 elements. sorted 25 elements.

19 16 14 16 20 6 17 13 8 39 18 0 26 46 45 17 7 46 45 29 15 38 43 19 17 0 2 4 7 12 12 12 14 16 17 20 22 22 23 26 29 30 32 33 37 38 38 43 43 46

you passing argument first thread, array, , overwriting contents of struct arguments sec thread. both threads hence see arguments sec thread.

what should have 2 separate arguments. illustration create array array of 2 structs , pass &array[0] first thread , &array[1] sec thread.

also, unsafe declare array in scope of loop. 1 time loop ends, variable out of scope , threads may read dead variable. should declare array @ function level remains live threads access it.

c++ c multithreading sorting pthreads

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -