【问题标题】:Passing struct data arguments to threads将结构数据参数传递给线程
【发布时间】:2021-06-30 21:07:28
【问题描述】:

我对如何将结构参数传递给 for 循环中的线程感到困惑。

当我尝试使用这种方法时,我得到了垃圾端口值。当我尝试在没有指针的情况下将 struct 更改为 astruct argstruct; 时,第二个端口会覆盖第一个端口,因此我得到了 200 200 打印。

另外,我是否必须 free mainFunc 中的结构,或两者兼而有之?

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void* Func(void* pstruct);

typedef struct thread_args{
    int port;
} astruct;

int main()
{
    int peers[2] = {100,200};
    pthread_t threads[2];
    astruct *argstruct[2];
    for (int i = 0; i < 2; i++) {
        argstruct[i] = malloc(sizeof(astruct));
        argstruct[i]->port = peers[i];
        pthread_create(&threads[i],NULL,Func,&argstruct[i]);
    }
    for(int i = 0; i < 2; i++){
        pthread_join(threads[i], NULL);
    }

    return 0;
}

void* Func(void* pstruct){
    int port;
    astruct *argstruct = (astruct *)pstruct;
    
    port = argstruct->port;
    printf("port: %d\n", port);
    return 0;
}

【问题讨论】:

  • @JanezKuhar 当你这样做时:Func [无括号]它函数的地址&amp; 没有伤害,但使用 [仅] Func 更规范。它允许Func 成为函数指针(例如):void *(*Func)(void *) = otherFunc;Func 可以传递给pthread_create(例如)pthread_create(&amp;threads[i], NULL, Func, argstruct[i]); 因此,函数地址和指向函数的指针可以可以互换使用。

标签: c memory-management pthreads


【解决方案1】:

我对如何将结构参数传递给 for 循环中的线程感到困惑。

argstruct[i]元素是指针,不需要地址操作符:

pthread_create(&threads[i], NULL, Func, argstruct[i]);

请注意,对于这种简单的情况,您不需要分配内存,您可以使用本地数组:

//...
astruct argstruct[2];
for (int i = 0; i < 2; i++) {   
    argstruct[i].port = peers[i];
    pthread_create(&threads[i], NULL, Func, &argstruct[i]);
}
//...

另外,我必须free main、Func 或两者中的结构吗?

您应该只释放一次。过程总是一样的,当你不再需要它时释放它,可以在线程例程中或main中。

在您的示例中,您可以很好地在 port = argstruct-&gt;port; 之后释放内存,因为在此分配之后您不再使用它:

void* Func(void* pstruct){
    int port;
    astruct *argstruct = (astruct *)pstruct;
    
    port = argstruct->port;
    free(argstruct); //<-- here
    printf("port: %d\n", port);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-04-17
    • 1970-01-01
    • 2011-02-18
    • 2017-05-25
    • 2015-03-08
    • 2014-01-05
    • 1970-01-01
    相关资源
    最近更新 更多