【发布时间】:2019-11-22 06:51:37
【问题描述】:
我在 C++ 中为多线程排序应用程序编写了代码,该应用程序使用随机数数组进行合并排序,但我无法对此进行测试,因为存在“分段错误(核心转储)”。我认为 main 函数有问题,但我不知道代码的哪一部分有问题。
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#define MAX 20
#define THREAD_MAX 2
using namespace std;
int a[MAX]; //array for test
int part = 0;
void merge(int low, int mid, int high)
{
//merge function for merge 2 parts
}
void merge_sort(int low, int high)
{
//merge sort function
}
void* merge_sort(void* arg)
{
//thread function for multithreading
}
int main()
{
for (int i = 0; i < MAX; i++)
a[i] = rand() % 100;
pthread_t threads[THREAD_MAX];
for (int i = 0; i < THREAD_MAX; i++)
pthread_create(&threads[i], NULL, merge_sort, (void*)NULL);
for (int i = 0; i < 4; i++)
pthread_join(threads[i], NULL);
merge(0, (MAX / 2 - 1) / 2, MAX / 2 - 1);
merge(MAX / 2, MAX / 2 + (MAX - 1 - MAX / 2) / 2, MAX - 1);
merge(0, (MAX - 1) / 2, MAX - 1);
// displaying sorted array
cout << "Sorted array: ";
for (int i = 0; i < MAX; i++)
cout << a[i] << " ";
return 0;
}
我尝试在linux上测试并使用此命令进行编译
g++ -pthread filename.cpp
【问题讨论】:
标签: c++ linux multithreading