【问题标题】:How to save pthread_t id to an array如何将 pthread_t id 保存到数组中
【发布时间】:2013-01-04 10:10:51
【问题描述】:

如何将 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 排序的线程

【问题讨论】:

标签: c pthreads


【解决方案1】:

所有线程都将收到相同的 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]);
}

【讨论】:

    【解决方案2】:
    I'll have to sort this array and then i'll have to execute first all the thread 
    ordered by id
    

    pthread_create 已经按照 man 的说明执行了一个线程:

    The  pthread_create() function starts a new thread in the calling process.
    

    所以你的循环已经启动了 N 个线程。此外,您不能指定线程 id,它们会在创建线程时返回。

    【讨论】:

      【解决方案3】:

      您不需要保存数组。您只需定义一个函数f,您希望对这些数字进行操作,然后,就像您在pthread_create() 中所做的那样,将该函数f 作为输入。

      每次调用pthread_create() 时,都会执行函数f

      【讨论】:

        猜你喜欢
        • 2011-01-12
        • 2018-02-04
        • 2021-11-30
        • 2015-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-08
        相关资源
        最近更新 更多