96 lines
2.5 KiB
C
96 lines
2.5 KiB
C
|
/*
|
||
|
编写一个程序, 创建多个线程, 每个线程负责对一个共享数组的不同部分进行排序。要求实现线程间的同步, 确保每个线程在进行排序时不会干扰其他线程的工作。
|
||
|
*/
|
||
|
#include <stdio.h>
|
||
|
#include <pthread.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <unistd.h>
|
||
|
|
||
|
typedef struct array_s
|
||
|
{
|
||
|
int *arr; // 数组元素头指针
|
||
|
int start_pos; // 起始位置
|
||
|
int end_pos; // 结束位置
|
||
|
pthread_mutex_t *mutex; // 互斥锁
|
||
|
} ARRAY;
|
||
|
|
||
|
void *sort(void *data)
|
||
|
{
|
||
|
ARRAY *array = (ARRAY *)data;
|
||
|
pthread_mutex_lock(array->mutex); // 线程加锁
|
||
|
printf("%ld 线程开始排序\n", pthread_self());
|
||
|
|
||
|
for (int i = array->start_pos; i < array->end_pos; i++)
|
||
|
{
|
||
|
for (int j = array->start_pos; j < array->end_pos - i; j++)
|
||
|
{
|
||
|
if (array->arr[j] > array->arr[j + 1])
|
||
|
{
|
||
|
array->arr[j] ^= array->arr[j + 1];
|
||
|
array->arr[j + 1] ^= array->arr[j];
|
||
|
array->arr[j] ^= array->arr[j + 1];
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pthread_mutex_unlock(array->mutex); // 线程解锁
|
||
|
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
int arr[9] = {1, 4, 2, 9, 0, 5, 6, 1, 8};
|
||
|
pthread_mutex_t mutex;
|
||
|
pthread_mutex_init(&mutex, NULL);
|
||
|
|
||
|
ARRAY array1 = {arr, 0, 2, &mutex};
|
||
|
ARRAY array2 = {arr, 3, 5, &mutex};
|
||
|
ARRAY array3 = {arr, 6, 8, &mutex};
|
||
|
|
||
|
pthread_t t1, t2, t3;
|
||
|
pthread_create(&t1, NULL, sort, &array1);
|
||
|
pthread_create(&t2, NULL, sort, &array2);
|
||
|
pthread_create(&t3, NULL, sort, &array3);
|
||
|
|
||
|
pthread_join(t1, NULL);
|
||
|
pthread_join(t2, NULL);
|
||
|
pthread_join(t3, NULL);
|
||
|
|
||
|
// 合并排序结果
|
||
|
int merged[9];
|
||
|
int i = 0;
|
||
|
for (int j = array1.start_pos; j <= array1.end_pos; j++)
|
||
|
{
|
||
|
merged[i++] = arr[j];
|
||
|
}
|
||
|
for (int j = array2.start_pos; j <= array2.end_pos; j++)
|
||
|
{
|
||
|
merged[i++] = arr[j];
|
||
|
}
|
||
|
for (int j = array3.start_pos; j <= array3.end_pos; j++)
|
||
|
{
|
||
|
merged[i++] = arr[j];
|
||
|
}
|
||
|
|
||
|
pthread_mutex_unlock(&mutex); // 解锁
|
||
|
|
||
|
// 创建数组结构和新线程,将合并后的数组进行排序
|
||
|
ARRAY arr4 = {merged, 0, 8, &mutex};
|
||
|
pthread_t t4;
|
||
|
pthread_create(&t4, NULL, sort, &arr4);
|
||
|
pthread_join(t4, NULL);
|
||
|
|
||
|
// 输出排序结果
|
||
|
printf("排序后的数组:");
|
||
|
for (int i = 0; i < 9; i++)
|
||
|
{
|
||
|
printf("%d ", merged[i]);
|
||
|
}
|
||
|
printf("\n");
|
||
|
|
||
|
pthread_mutex_destroy(&mutex); // 销毁互斥锁
|
||
|
|
||
|
return 0;
|
||
|
}
|