Can you call qsort on section of an array or matrix in row major order?
I would like to call qsort on separate parts of an array within pthreads, is this thread safe and okay to do?
I am working on separating the given array or matrix by the amount of threads or cores given as a global variable n_threads
and then calling qsort on each section in the same arrays memory. I want to use a start value and a total values to get the start and end index of the qsort function.
// @Return - returns a comparison function for quicksort
int cmp_func (const void * a, const void * b) {
return ( *(float*)a - *(float*)b );
}
// struct used for passing arguments from merge_sort to merge_sort recursively
typedef struct {
float* m;
size_t t_id;
} t_arg_sort;
// Initalises a new sorted matrix within threads.
static void* pthread_sorted(void* arg) {
t_arg_sorted* t_arg = (t_arg_sorted*) arg;
const size_t start = t_arg->t_id * (n_elements/n_threads);
qsort(t_arg->r + start, (n_elements/n_threads), sizeof(float), cmp_func);
return NULL;
}
// Sorts matrix
float* sorted(const float* matrix) {
float* new_matrix = new_matrix();
t_arg_sort thread_args[n_threads];
for (size_t i = 0; i < n_threads; i++) {
thread_args[i] = (t_arg_sort) {
.m = new_matrix,
.t_id = i
};
}
// create threads to sort matrix
pthread_t threads[n_threads];
for (size_t i = 0; i < n_threads; i++) {
if(pthread_create(threads + i, NULL, pthread_reversed, thread_args + i) != 0) {
perror("Create thread failed!\n");
return 1;
}
}
// join threads after all coordinates have been initialised
for (size_t i = 0; i < n_threads; i++) {
if (pthread_join(threads[i], NULL) != 0) {
perror("Join thread failed!\n");
return 1;
}
}
qsort(new_matrix, g_elements, sizeof(float), cmp_func);
return new_matrix;
}