且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

pthread_create 并传递一个整数作为最后一个参数

更新时间:2022-12-09 17:25:39

以 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.