使用多个线程平移数字

时间:2016-02-29 01:40:59

标签: c multithreading pthreads

我试图将数字1 - 10,000与8个线程对齐。为了澄清,我希望第一个线程做1 ^ 2,第二个线程做2 ^ 2,...,第8个线程做8 ^ 2,第一个线程要做9 ^ 2 ......等问题我是具有的是,而不是上述发生,每个线程计算1-10,000的平方。

我的代码如下。我有标记的部分,我宁愿那些回答不修改。提前感谢任何提示!

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>

#define NUMBER_OF_THREADS 8
#define START_NUMBER 1
#define END_NUMBER 10000

FILE *f;

void *sqrtfunc(void *tid) { //function for computing squares
    int i;
    for (i = START_NUMBER; i<=END_NUMBER; i++){
        fprintf(f, "%lu squared = %lu\n", i, i*i);
    }
}

int main(){
    //Do not modify starting here
    struct timeval start_time, end_time;
    gettimeofday(&start_time, 0);
    long unsigned i;
    f = fopen("./squared_numbers.txt", "w");
    //Do not modify ending here

    pthread_t mythreads[NUMBER_OF_THREADS]; //thread variable
    long mystatus;

    for (i = 0; i < NUMBER_OF_THREADS; i++){ //loop to create 8 threads
        mystatus = pthread_create(&mythreads[i], NULL, sqrtfunc, (void *)i);
        if (mystatus != 0){ //check if pthread_create worked
            printf("pthread_create failed\n");
            exit(-1);
        }
    }
    for (i = 0; i < NUMBER_OF_THREADS; i++){
        if(pthread_join(mythreads[i], NULL)){
            printf("Thread failed\n");
        }
    }
    exit(1);

    //Do not modify starting here
    fclose(f);
    gettimeofday(&end_time, 0);
    float elapsed = (end_time.tv_sec-start_time.tv_sec) * 1000.0f + \
                    (end_time.tv_usec-start_time.tv_usec) / 1000.0f;
    printf("took %0.2f milliseconds\n", elapsed);
    //Do not modify ending here
}

0 个答案:

没有答案