在发送整数(不是从堆)作为线程参数时的行为

问题描述 投票:2回答:1

我想从同一函数创建具有不同索引值的线程。我总是将变量从堆发送到线程。但是我不想从堆中发送数据,因为我想在这里发送一个不同的变量来了解所有变量的索引。在这种情况下,如果我从堆发送,则索引值可能会在其他值中更改而尚未存储。

#include <pthread.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>

struct Myarg{
    int index;
};

void *foo(void *arg)
{
    struct Myarg *a = (struct Myarg* ) arg;
    printf("\nfoo%d executed", a->index);
    pthread_exit(NULL);
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t tid[6];

    struct Myarg arg;

    for (int i = 0; i < 6; i++)
    {
        arg.index = i;
        if (pthread_create(&tid[i], NULL, foo, &arg) != 0)
        {
            printf("\nerror!");
            exit(-1);
        }
    }

    for (int i = 0; i < 6; i++)
    {
        if (pthread_join(tid[i], NULL) != 0)
        {
            printf("\nerror!");
            exit(-1);
        }
    }

    return 0;
}

以下是此代码的几个输出:

foo1 executed
foo2 executed
foo3 executed
foo4 executed
foo5 executed
foo5 executed

foo1 executed
foo4 executed
foo3 executed
foo5 executed
foo5 executed
foo2 executed

我分享此代码只是为了表明我的意图。这是我预期的各种结果的示例:

foo1 executed
foo4 executed
foo3 executed
foo5 executed
foo6 executed
foo2 executed

我想我可以通过从堆中获取整数并创建所有六个不同的参数变量来实现此目的。但是我想知道这里到底发生了什么?还是可以在不创建6个不同变量的情况下实现这一目标?

c multithreading arguments pthreads parameter-passing
1个回答
0
投票

您正在将same结构的地址发送到线程的[[each。这意味着您有一个竞争条件,关于每个线程读取该结构时该结构恰好包含的值。最简单的解决方案是拥有一个结构数组,并将每个不同的数组元素传递给每个数组。

struct Myarg arg[6]; for (int i = 0; i < 6; i++) { arg[i].index = i; if (pthread_create(&tid[i], NULL, foo, &arg[i]) != 0) { printf("\nerror!"); exit(-1); } }

而且,您不会在代码的任何地方使用堆,因为您从不会调用任何malloc函数家族。所有相关变量都是局部变量(在大多数实现中)都存在于堆栈中。
© www.soinside.com 2019 - 2024. All rights reserved.