【问题标题】:How to dynamically allocate(initialize) a pthread array?如何动态分配(初始化)一个 pthread 数组?
【发布时间】:2014-11-05 09:47:23
【问题描述】:

我有一个 pthread 指针,我需要为指针分配足够的空间来容纳足够数量的 pthread。然后初始化它们和 pthread_create() 以将线程传递给一些函数。

问题是,如果我只是使用malloc给指针分配空间,然后只是使用pointer[index] pthread_create,那么线程将无法正确创建。我该如何解决这个问题?我相信 pthread_t 是某种类型的结构,所以我相信我需要在执行 pthread 之前初始化它们。我怎么做?谢谢。

我刚刚测试了一定数量的 pthread,它们工作正常:

pthread_t t1, t2, t3 ...... tn;

然后

pthread_create(&t1, NULL, function, (void *)argument)

但如果我使用指针和 malloc,它们将无法工作。不会创建线程。

pthread_t *ptr;

ptr = malloc(sizeof(pthread_t)*num);

然后

pthread_create(&ptr[index], NULL, function, (void *)argument)

不会工作。在这种情况下如何初始化 ptr[index] ?

【问题讨论】:

  • pthread_t 是一些未指定的类型。在我的 Debian/Linux 系统上,它是 long... 而 malloc 可能会失败。你测试过吗?最后,您应该清除ptr 数组...但是pthread_create 可能会失败,您应该对其进行测试。
  • 您的 malloc 解决方案似乎是正确的。问题可能出在其他地方。
  • 请编辑您的问题以使用真实代码进行改进。
  • “不起作用”。请继续描述问题。

标签: c pthreads


【解决方案1】:

是的,它应该可以工作。你的some space 是什么?

你没有放完整的代码,只是一个建议,你初始化num了吗?

检查以下代码。我相信它有效。

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void* func(void* id)
{
        int *c;
        c = (int*)id;
        if(c)
                printf("%d\n", *c);
}

int main(int argc, char *argv[])
{
        int i = 0;
        int *index = NULL;
        int num;
        pthread_t *ptr;
        if (argv[1])
                num = atoi(argv[1]);

        index = calloc (num, sizeof (int));
        for(i = 0; i < num; i++)
        {
                index[i] = i;
        }

        ptr = malloc(sizeof(pthread_t)*num);
        for(i = 0; i < num; i++)
        {
                pthread_create(&ptr[i], NULL, func, (void*)&index[i]);
        }
        for(i = 0; i < num; i++)
                pthread_join(ptr[i], NULL);

        return 0;
}

【讨论】:

    【解决方案2】:

    和你动态分配整数数组一样……

    pthread_t  *id_array;
    
    id_array = (pthread_t*)malloc(sizeof(pthread_t)*n); 
    

    其中 n = 数组大小 ...

    它会为你工作..

    【讨论】:

    • 他需要初始化而不是分配内存
    猜你喜欢
    • 1970-01-01
    • 2020-05-04
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    相关资源
    最近更新 更多