无法生成大量随机整数而不会溢出

时间:2019-02-07 21:02:20

标签: c multithreading random heap stack-overflow

我创建了使用多线程快速排序的排序算法。输入数据是随机创建的。 1亿个整数被随机化并插入到数组中,然后进行排序。事实是,我想测试输入更多数据时算法复杂度的增长速度。

问题:1亿个数字是我可以生成和/或将它们插入数组的数字的上限。 问题:如何增加堆栈/堆的大小以允许使用更多的数字。我计划做一千亿。 P.S RAM没问题。

定义生成整数数量的部分,将其写在以下行上:“ //生成整数数量”。

谢谢。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <pthread.h>
struct Params
{
    int *start;
    size_t len;
       int depth;
};
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
void *merge_sort_thread(void *pv);
void merge(int *start, int *mid, int *end)
{
    int *res = malloc((end - start)*sizeof(*res));
    int *lhs = start, *rhs = mid, *dst = res;
    while (lhs != mid && rhs != end)
        *dst++ = (*lhs < *rhs) ? *lhs++ : *rhs++;
    while (lhs != mid)
        *dst++ = *lhs++;
    // copy results
    memcpy(start, res, (rhs - start) * sizeof *res);
    free(res);
}
// initialization
   void merge_sort_mt(int *start, size_t len, int depth)
{
    if (len < 2)
        return;
    if (depth <= 0 || len < 4)
    {
          merge_sort_mt(start, len/2, 0);
        merge_sort_mt(start+len/2, len-len/2, 0);
    }
    else
    {
        struct Params params = { start, len/2, depth/2 };
        pthread_t thrd;
        pthread_mutex_lock(&mtx);
        printf("Starting subthread...\n");
        pthread_mutex_unlock(&mtx);
        pthread_create(&thrd, NULL, merge_sort_thread, &params);
        merge_sort_mt(start+len/2, len-len/2, depth/2);
        pthread_join(thrd, NULL);
        pthread_mutex_lock(&mtx);
        printf("Finished subthread.\n");
        pthread_mutex_unlock(&mtx);
    }
    merge(start, start+len/2, start+len);
}
void *merge_sort_thread(void *pv)
{
    struct Params *params = pv;
    merge_sort_mt(params->start, params->len, params->depth);
    return pv;
}
void merge_sort(int *start, size_t len)
{
    merge_sort_mt(start, len, 8);
}
int main()
{
clock_t start, stop;
    static const unsigned int N = 100000000; //number of generated integers
    int *data = malloc(N * sizeof(*data));
    unsigned int i;
    srand((unsigned)time(0));
    for (i=0; i<N; ++i)
    {
    data[i] = rand() % 500;
  //  printf("%4d ", data[i]);
   //     if ((i+1)%8 == 0)
          // printf("\n");
    }
  //  printf("\n");
   start = clock();
    merge_sort(data, N);
    for (i=0; i<N; ++i)
    {
       // printf("%4d ", data[i]);
     //   if ((i+1)%8 == 0)
        //    printf("\n");
    }
   stop = clock();
       printf("Elapsed: %f seconds\n", (double)(stop - start) / CLOCKS_PER_SEC);
   // printf("\n");
    free(data);
    getchar();
    getchar();
    getchar();
    getchar();
    getchar();
    return 0;
}

0 个答案:

没有答案