我正在做一个练习,它最终会变成一个pthread实验,用于教育目的在这里,我将获取一个列表(字母表),并尝试获取五个数字列表,这些列表可以提供给一个pthread来分析一些东西例如,字母表中的numList = 0 5 10 15 20 25最后,我将设置它,这样pthread将获取该列表并将列表中这些位置的元素与其他内容进行比较我创建了一个divList函数来尝试返回上面的列表,以便使用它尽管我在函数中得到了正确的结果,但我不会将列表返回到main我处理指针和函数的方式有明显的错误吗?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>

#define num_threads 5

/* Global variable: accessible to all threads */
char *list = "abcdefghijklmnopqrstuvwxyz";
/* ----------------------------------------- */

int *divList(int MAX, int pos);
void* Hello(void* rank); /* Thread Function */

int main(int argc, char *argv[])
{
    int i, n, thread;
    pthread_t* thread_handles;

    n = strlen(list);
    for (i = 0; i < num_threads; i++){
        if (i <= n % num_threads) // str length / 5 ... remainder
             //  = 0, 1, 2, 3, 4
            printf("elements: %d\n", divList(n + 1, i));
        else{
            printf("elements: %d\n", divList(n, i));
        }
    }

    thread_handles = malloc (num_threads*sizeof(pthread_t));

    for (thread = 0; thread < num_threads; thread++){
        pthread_create(&thread_handles[thread], NULL, Hello,
         (void*) thread);
    }

    printf("Hello from the main thread\n");

    for (thread = 0; thread < num_threads; thread++)
        pthread_join(thread_handles[thread], NULL);
    free(thread_handles);
    return 0;
}   /* MAIN */

int *divList(int MAX, int pos)
{
    int i = 0, j;
    int *numList = malloc(MAX + 1);

    for (j = pos; j < MAX; (j = j + num_threads)){
        numList[i] = j;
        printf("test list: %d\n", numList[i]);
        i++;
    }
    return numList;
}

void* Hello(void* rank) {
    int my_rank = (int) rank;
    printf("Hello from  thread %d of %d\n", my_rank, num_threads);

    return NULL;
}   /* Hello */

最佳答案

divList()返回一个指针,指向int数组的第1个元素,元素数等于作为第一个参数加1传入的元素数,下面的代码将其存储在devList()中。
要访问这些值,可以将指针视为数组,例如循环打印其值:

void printList(int * plist, size_t s)
{
  for (size_t i = 0; i < s; ++i)
  {
    printf("element[%zu]: %d\n", i, plist[i];
  }
}

int main(int argc, char *argv[])
{
  int i, n, thread;
  int *plist = NULL;
  pthread_t *thread_handles;

  n = strlen(list);
  for (i = 0; i < num_threads; i++)
  {
    if (i <= n % num_threads)
    {
      plist = divList(n + 1, i);
      printList(plist, n + 1);  /* divList allocates one more then needed
                                   but never initialises it, so do not print it. */
    }
    else
    {
      ..

10-07 14:48
查看更多