Предупреждения компилятора C на pthread_create - PullRequest
0 голосов
/ 23 ноября 2018

Я не понимаю справочную страницу для thread_create.Что такое пустота * nullable?Я не могу сделать индекс массива глобальной переменной для этой программы.Аргумент, передаваемый потокам, должен использоваться в вычислении Фибоначчи.Я думаю, что каким-то образом мне нужно получить индекс (или указатель на индекс), переданный и обработанный потоком, чтобы получить вычисление Фибоначчи.Вот мои предупреждения:

fibonacci.c:46:31: warning: incompatible pointer types passing 'void *(int)' to parameter of type
      'void * _Nullable (* _Nonnull)(void * _Nullable)' [-Wincompatible-pointer-types]
                pthread_create(&thread, &a, run, i);
                                            ^~~
/usr/include/pthread.h:328:31: note: passing argument to parameter here
                void * _Nullable (* _Nonnull)(void * _Nullable),
                                            ^
fibonacci.c:46:36: warning: incompatible integer to pointer conversion passing 'int' to parameter
      of type 'void *' [-Wint-conversion]
                pthread_create(&thread, &a, run, i);
                                             ^
/usr/include/pthread.h:329:30: note: passing argument to parameter here
                void * _Nullable __restrict);

Я изначально сделал индекс глобальной переменной, но мне сказали, что это недопустимо, потому что это делает потоки бесполезными.Я не уверен, как еще изменить цикл.Смысл этой программы - упражнение в элементарной многопоточности, поэтому я мог бы использовать мьютекс или семафор, но я подумал, что объединение потоков будет самым простым, но я не могу понять, как передать целенаправленный аргумент потокам.Есть идеи?Вот мой неработающий код:

#include<stdio.h> //for printf
#include<stdlib.h>  //for malloc
#include<pthread.h> //for threading

#define SIZE 25 //number of fibonaccis to be computed
int *fibResults;  //array to store fibonacci results

void *run(int arg)  //executes and exits each thread
{
  if (arg == 0)
  {
    fibResults[arg] = 0;
    printf("The fibonacci of %d= %d\n", arg, fibResults[arg]);    
    pthread_exit(0); 
 }

  else if (arg == 1)
  {
    fibResults[arg] = 1;
    printf("The fibonacci of %d= %d\n", arg, fibResults[arg]);   
    pthread_exit(0);  
  }
  else
  {
    fibResults[arg] = fibResults[arg -1] + fibResults[arg -2];
    printf("The fibonacci of %d= %d\n", arg, fibResults[arg]);
    pthread_exit(0);
  }
}

//main function that drives the program.
int main()
{
  pthread_attr_t a;
  fibResults = (int*)malloc (SIZE * sizeof(int));
  pthread_attr_init(&a);

  for (int i = 0; i < SIZE; i++)
  {
    pthread_t thread;
    pthread_create(&thread, &a, run, i);
    printf("Thread[%d] created\t", i); 
    fflush(stdout);
    pthread_join(thread, NULL);
    printf("Thread[%d] joined & exited\t", i); 
  }
  return 0;
}

Я пытаюсь следовать советам ММ и получаю новые ошибки и предупреждения с этим кодом:

#include<stdio.h> //for printf
#include<stdlib.h>  //for malloc
#include<pthread.h> //for threading

#define SIZE 25 //number of fibonaccis to be computed
int *fibResults;  //array to store fibonacci results

void *run(void *arg)  //executes and exits each thread
{
  if (arg == 0)
  {
    fibResults[arg] = 0;
    printf("The fibonacci of %d= %d\n", *arg, fibResults[*arg]);    
    pthread_exit(0); 
 }

  else if (arg == 1)
  {
    fibResults[*arg] = 1;
    printf("The fibonacci of %d= %d\n", *arg, fibResults[*arg]);   
    pthread_exit(0);  
  }
  else
  {
    fibResults[*arg] = fibResults[*arg -1] + fibResults[*arg -2];
    printf("The fibonacci of %d= %d\n", *arg, fibResults[*arg]);
    pthread_exit(0);
  }
}

//main function that drives the program.
int main()
{
  pthread_attr_t a;
  fibResults = (int*)malloc (SIZE * sizeof(int));
  pthread_attr_init(&a);

  for (int i = 0; i < SIZE; i++)
  {
    pthread_t thread;
    pthread_create(&thread, &a, run, &fibResults[i]);
    printf("Thread[%d] created\t", fibResults[i]); 
    fflush(stdout);
    pthread_join(thread, NULL);
    printf("Thread[%d] joined & exited\t", i); 
  }
  return 0;
}

Вот что происходит, когдаЯ компилирую:

gcc -o fibonacci fibonacci.c
fibonacci.c:17:15: error: array subscript is not an integer
    fibResults[arg] = 0;
              ^~~~
fibonacci.c:18:57: error: array subscript is not an integer
    printf("The fibonacci of %d= %d\n", *arg, fibResults[*arg]);    
                                                        ^~~~~
fibonacci.c:22:16: warning: comparison between pointer and integer ('void *' and 'int')
  else if (arg == 1)
           ~~~ ^  ~
fibonacci.c:24:15: error: array subscript is not an integer
    fibResults[*arg] = 1;
              ^~~~~
fibonacci.c:25:57: error: array subscript is not an integer
    printf("The fibonacci of %d= %d\n", *arg, fibResults[*arg]);   
                                                        ^~~~~
fibonacci.c:30:15: error: array subscript is not an integer
    fibResults[*arg] = fibResults[*arg -1] + fibResults[*arg -2];
              ^~~~~
fibonacci.c:30:40: error: invalid operands to binary expression ('void' and 'int')
    fibResults[*arg] = fibResults[*arg -1] + fibResults[*arg -2];
                                  ~~~~ ^~
fibonacci.c:30:62: error: invalid operands to binary expression ('void' and 'int')
    fibResults[*arg] = fibResults[*arg -1] + fibResults[*arg -2];
                                                        ~~~~ ^~
fibonacci.c:31:57: error: array subscript is not an integer
    printf("The fibonacci of %d= %d\n", *arg, fibResults[*arg]);
...