c - 如何将 pthread_t id 保存到数组

标签 c pthreads

如何将 p_thread 的 id 保存到数组中?

int i;
pthread_t t[N];
float arrayId[N];


for (i = 0; i < N; i++) {
    pthread_create(&t[i], NULL, f, (void *) &i);
    printf("creato il thread id=%lu\n", t[i]);
    arrayId[i] = t[i];
    printf("a[%d]=%f\n", i, arrayId[i]);
}

我可以打印,但我无法保存...

我必须对这个数组进行排序,然后我必须首先执行按 id 排序的所有线程

最佳答案

所有线程将收到相同的值 i因为您是按值传递它(相同的地址)。
这应该解决它:

int i;
pthread_t t[N];
float arrayId[N];

int indexes[N];

for (i = 0; i < N; i++) {
    indexes[i] = i;
    pthread_create(&t[i], NULL, f, (void *) &indexes[i]);
    printf("creato il thread id=%lu\n", t[i]);
    arrayId[i] = t[i];
    printf("a[%d]=%f\n", i, arrayId[i]);
}

关于c - 如何将 pthread_t id 保存到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14155055/

相关文章:

c - 循环文本文件时出现不需要的字符

c - difftime的粒度

CMAKE/MAKEFILE :/usr/bin/x86_64-linux-gnu-ld : Cannot find -lfftw3f

c - pthreads : difference due to malloc and direct declaration

c - 如何对动态分配的数据进行 const 限定?

c++ - 您将如何缩短它以便 action1 和 action2 在代码中只出现一次?

c++ - std::thread 相对于 C++ 中 pthread 的优势

c++ - 为什么在使用 MinGW 添加 ltalloc 时会出现段错误

c++ - 使用 visual stdio2008 的线程

php - 如何使用 pthreads 重新编译 PHP7