为平方根操作创建多线程

时间:2016-03-01 03:15:09

标签: c multithreading pthreads

我正在尝试创建启动8个线程的C程序,每个线程都是平方根。 8个线程需要处理从1到10000开始的所有数字并输出到.txt文件中。我创建了这段代码但有很多错误。请提供所需的任何帮助/提示。

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

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


FILE *f;

void *square_operation(void *tid)
{

for (i=(START_NUMBER+tid); i<=END_NUMBER; i++) {
    fprintf(f, "%lu squared = %lu\n", i, i*i);
    i+=7;
}
pthread_exit(NULL);
}

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

/* The main program creates 8 threads and then exits */
pthread_t threads[NUMBER_OF_THREADS];
long status, i;
for (i=0; i<NUMBER_OF_THREADS; i++)
{
    status = pthread_create(&threads[i], NULL, square_operation, (void *)i);
    if (status != 0)
    {
        printf("Oops. pthread_create returned error code %0d\n", status);
        exit(-1);
    }
}

/* Wait for all threads to finish, before exiting process */
for (i=0; i<NUMBER_OF_THREADS; i++)
{
    if (pthread_join(threads[i], NULL))
    { printf("Thread %0d failed to join\n"); }
}
exit(1);


// START: Do not modify anything 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);
// END: Do not modify anything here
}

所以我得到了这些错误:

prog2.c:16:10: error: use of undeclared identifier 'i'
    for (i=(START_NUMBER+tid); i<=END_NUMBER; i++) {
         ^
prog2.c:16:32: error: use of undeclared identifier 'i'
    for (i=(START_NUMBER+tid); i<=END_NUMBER; i++) {
                               ^
prog2.c:16:47: error: use of undeclared identifier 'i'
    for (i=(START_NUMBER+tid); i<=END_NUMBER; i++) {
                                              ^
prog2.c:17:43: error: use of undeclared identifier 'i'
        fprintf(f, "%lu squared = %lu\n", i, i*i);
                                          ^
prog2.c:18:9: error: use of undeclared identifier 'i'
        i+=7;
        ^
prog2.c:33:18: error: redefinition of 'i' with a different type: 'long' vs
      'unsigned long'
    long status, i;
                 ^
prog2.c:27:19: note: previous definition is here
    long unsigned i;
                  ^
prog2.c:39:70: warning: format specifies type 'int' but the argument has type
      'long' [-Wformat]
            printf("Oops. pthread_create returned error code %0d\n", status);
                                                             ~~~     ^~~~~~
                                                             %0ld
prog2.c:48:28: warning: more '%' conversions than data arguments [-Wformat]
        { printf("Thread %0d failed to join\n"); }

1 个答案:

答案 0 :(得分:0)

你没有在方形操作中声明任何名为i的变量。 也许在main中,但由于c的范围机制,它在sqare操作中不可见。 这应该会减少编译器错误日志。