c - How to sort an array of n elements using n - 1 threads -
i have sort array of n elements using n - 1 threads. each thread test boolean flags equal 0 elements in position i , i+1 have swapped, otherwise set 1. every thread body function ends if elements in right position, flags equal 1.
following main function create threads , join them (some variables global):
int i; pthread_t threads[n - 1]; // init array random values array = init_array(n); len = n; // flags check if array sorted is_array_sorted = 0; is_sorted = calloc(n - 1, sizeof(int)); // prints initial array print_array(array, n); // init mutex pthread_mutex_init(&lock, null); // create n - 1 threads (i = 0; < n - 1; i++) { if (pthread_create(&threads[i], null, swap, (void*)&i) != 0) exit(exit_failure); } // waits until threads end (i = 0; < n - 1; i++) { if (pthread_join(threads[i], null) != 0) exit(exit_failure); } // destroy mutex pthread_mutex_destroy(&lock); // prints sorted array print_array(array, n); // free memory free(array); free(is_sorted); and thread body function:
static void* swap(void* args) { // indiex of element check (j , j+1) int j = *((int*)args); // while array not sorted while (1) { int i; // start mutual exclusion pthread_mutex_lock(&lock); // check if have swap elements if (array[j] > array[j+1]) { // swap elements int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } // elements in position j , j+1 in right order is_sorted[j] = 1; is_array_sorted = 1; // check if elements sorted (i = 0; < len - 1; i++) { if (is_sorted[i] == 0) { is_array_sorted = 0; break; } } if (is_array_sorted) { // array sorted, terminate thread pthread_mutex_unlock(&lock); break; } pthread_mutex_unlock(&lock); } pthread_exit(null); } the problem program never ends. why? how can fix problem?
please note multithreading exercise performance, or best solution not required.
this code:
for (i = 0; < n - 1; i++) { if (pthread_create(&threads[i], null, swap, (void*)&i) != 0) is not doing think should doing. there 1 variable i, , passing address i threads. i being incremented each time launch thread. there no guarantee each thread see unique value when access data @ passed in address.
a hacky way deal pass in pointer value corresponds integer value want thread receive.
char *x = 0; (i = 0; < n - 1; i++) { if (pthread_create(&threads[i], null, swap, x++) != 0) the thread function decode this:
int j = (char*)args - (char *)0; as stated in comments, sorting approach highly undesirable, , should reworked. think teacher give high marks solution not think highly of abilities of students.
Comments
Post a Comment