本文介绍了pthread_create 并传递一个整数作为最后一个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能:

void *foo(void *i) {
    int a = (int) i;
}

int main() {
    pthread_t thread;
    int i;
    pthread_create(&thread, 0, foo, (void *) i);
}

在编译时,有一些关于强制转换的错误((void *) iint a = (int) i).如何正确传递一个整数作为 pthread_create 的最后一个参数?

At compilation, there are some errors about casting ((void *) i and int a = (int) i). How can I pass an integer as the last argument of pthread_create properly?

推荐答案

以 szx 的答案为基础(所以给他点赞),下面是它在您的 for 循环中的工作方式:

Building on szx's answer (so give him the credit), here's how it would work in your for loop:

void *foo(void *i) {
    int a = *((int *) i);
    free(i);
}

int main() {
    pthread_t thread;
    for ( int i = 0; i < 10; ++1 ) {
        int *arg = malloc(sizeof(*arg));
        if ( arg == NULL ) {
            fprintf(stderr, "Couldn't allocate memory for thread arg.\n");
            exit(EXIT_FAILURE);
        }

        *arg = i;
        pthread_create(&thread, 0, foo, arg);
    }

    /*  Wait for threads, etc  */

    return 0;
}

在循环的每次迭代中,您都在分配新的内存,每个内存都有不同的地址,因此在每次迭代中传递给 pthread_create() 的东西是不同的,因此您的线程最终会尝试访问相同的内存,并且您不会像只传递 i 的地址那样遇到任何线程安全问题.在这种情况下,您还可以设置一个数组并传递元素的地址.

On each iteration of the loop, you're allocating new memory, each with a different address, so the thing that gets passed to pthread_create() on each iteration is different, so none of your threads ends up trying to access the same memory and you don't get any thread safety issues in the way that you would if you just passed the address of i. In this case, you could also set up an array and pass the addresses of the elements.

这篇关于pthread_create 并传递一个整数作为最后一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 18:02