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

标签 c pthreads

我有以下功能:

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

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

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

最佳答案

基于 szx 的回答(所以请相信他),下面是它在 for 循环中的工作方式:

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 的地址那样遇到任何线程安全问题。在这种情况下,您还可以设置一个数组并传递元素的地址。

关于c - pthread_create 并传递一个整数作为最后一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19232957/

相关文章:

c - 在c中通过套接字发送结构

c - 在 C 中更多地了解 pthreads

c - 终止具有临界区代码的 POSIX 多线程应用程序的最佳方法是什么?

c++11 #include <thread> 给出编译错误

c - 为什么 linux 线程函数在 windows 中工作?

c - 为什么来自 main 的 Pthread 信号会挂起代码?

c++ - 在两个不同的输入数据集上运行同一个 C/C++ 程序的两个实例

c - 为什么 b 数组不复制整个 a 数组?

c - 如何分析 R 包中的底层 C 代码?

c - 在 C 中使用 Pthreads 互斥锁和条件变量进行同步