Я пытаюсь создать программу на C, которая инициирует 8 потоков, каждый поток выполняет квадратные корни. 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"); }
Каковы ошибки? – SSC
это ошибка 'prog2.c: 16: 10: ошибка: использование необъявленного идентификатора 'i' для (i = (START_NUMBER + tid); i <= END_NUMBER; i ++) {' –
Я знаю, что я объявил 'long unsigned i; 'в главном, но куски кода, который вы видите, я не могу изменить. –