在linux中使用线程池完成快速排序
时间: 2024-05-03 11:16:25 浏览: 103
linux下的线程池实现
4星 · 用户满意度95%
以下是在 Linux 中使用线程池完成快速排序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_THREADS 8
typedef struct {
int* array;
int left;
int right;
} quicksort_params_t;
typedef struct {
quicksort_params_t* params;
pthread_t thread_id;
} thread_data_t;
void swap(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
int partition(int* array, int left, int right) {
int pivot = array[right];
int i = left - 1;
for (int j = left; j <= right - 1; j++) {
if (array[j] <= pivot) {
i++;
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[right]);
return i + 1;
}
void quicksort(int* array, int left, int right) {
if (left >= right) return;
int pivot_index = partition(array, left, right);
quicksort(array, left, pivot_index - 1);
quicksort(array, pivot_index + 1, right);
}
void* quicksort_thread(void* arg) {
quicksort_params_t* params = (quicksort_params_t*) arg;
quicksort(params->array, params->left, params->right);
return NULL;
}
void quicksort_parallel(int* array, int left, int right, int num_threads) {
pthread_t threads[MAX_THREADS];
thread_data_t thread_data[MAX_THREADS];
int thread_count = 0;
quicksort_params_t params = { .array = array, .left = left, .right = right };
if (num_threads <= 1) {
quicksort(array, left, right);
return;
}
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int chunk_size = (right - left + 1) / num_threads;
int remainder = (right - left + 1) % num_threads;
int start_index = left;
for (int i = 0; i < num_threads; i++) {
int end_index = start_index + chunk_size - 1;
if (remainder > 0) {
end_index++;
remainder--;
}
params.left = start_index;
params.right = end_index;
thread_data[thread_count].params = ¶ms;
if (pthread_create(&threads[thread_count], &attr, quicksort_thread, ¶ms) != 0) {
printf("Error creating thread.\n");
exit(-1);
}
thread_count++;
start_index = end_index + 1;
}
pthread_attr_destroy(&attr);
for (int i = 0; i < thread_count; i++) {
if (pthread_join(threads[i], NULL) != 0) {
printf("Error joining thread.\n");
exit(-1);
}
}
}
int main() {
int array[] = { 3, 7, 2, 8, 1, 9, 6, 5, 4 };
int array_size = sizeof(array) / sizeof(array[0]);
printf("Unsorted array:\n");
for (int i = 0; i < array_size; i++) {
printf("%d ", array[i]);
}
printf("\n");
quicksort_parallel(array, 0, array_size - 1, 4);
printf("Sorted array:\n");
for (int i = 0; i < array_size; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
```
此代码实现了一个简单的快速排序,并使用线程池在 Linux 中并行执行。即使输入的数组很大,也可以在多个线程上分解排序操作,从而显著提高性能。
阅读全文