c中的平方和多线程

时间:2016-02-28 07:57:25

标签: c multithreading square-root

我正在编写一个程序,使用8个线程来对齐1到10000之间的数字。我已经编写了大部分代码,但我的问题是如何指定哪些线程对哪些数字进行平方。我也是新的多线程。澄清:

我使用8个线程将数字从1到100000平方并将它们写入文件。打开文件并关闭文件是可以的,但是从每个线程写出每个方块都是这里的等式的一部分。这是我的第一个使用pthread的程序,所以我假设你需要告诉每个线程按顺序排列的数字

理想情况下我想:

主题1:1 ^ 2

主题2:2 ^ 2

主题3:3 ^ 2

等通过10000 ...

在我的main函数中,创建函数然后等待线程完成的代码是这样的:

BundleTable.EnableOptimizations = true;

线程将运行的void函数是:

for (i = 0; i < NUMBER_OF_THREADS; i++) {
    printf("Main here. Creating thread %luu\n", i);
    status = pthread_create(&threads[i], NULL, square_root_integer, (void *) i);
    if (status != 0){
        printf("Error: pthread_create returned error code %0ld\n", status);
        exit (-1);
    }
}

for (i = 0; i < NUMBER_OF_THREADS; i++){
    if (pthread_join(threads[i], NULL)){
        printf("Thread %lu failed to join\n",i);
    }
}

所以在main函数中我需要传递需要平方到“square_integer”函数的数字。

任何帮助都会很棒,如果你们需要更多信息,请告诉我们!

1 个答案:

答案 0 :(得分:0)

让线程1对数字1,1 + 8,1 + 16,1 + 24,...
进行计算 和螺纹2的数字2,2 + 8,2 + 16,2 + 24,...,2 + 8 * n,...
和3号线的数字3,3 + 8,3 + 16,3 + 24,...,3 + 8 * n,...
等等。

通过这种方式,所有数字都得到了覆盖,并且工作在线程中得到了相当均匀的分布。