gpt4 book ai didi

c - 通过 pthread_create 传递整数值

转载 作者:太空狗 更新时间:2023-10-29 17:22:13 27 4
gpt4 key购买 nike

我只是想将一个整数的值传递给一个线程。

我该怎么做?

我试过:

    int i;
pthread_t thread_tid[10];
for(i=0; i<10; i++)
{
pthread_create(&thread_tid[i], NULL, collector, i);
}

线程方法如下所示:

    void *collector( void *arg)
{
int a = (int) arg;
...

我收到以下警告:

    warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

最佳答案

如果您不将 i 转换为空指针,编译器会报错:

pthread_create(&thread_tid[i], NULL, collector, (void*)i);

也就是说,将整数转换为指针并不是严格安全的:

ISO/IEC 9899:201x 6.3.2.3 Pointers

  1. An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

所以你最好将一个单独的指针传递给每个线程。

这是一个完整的工作示例,它向每个线程传递一个指向数组中单独元素的指针:

#include <pthread.h>
#include <stdio.h>

void * collector(void* arg)
{
int* a = (int*)arg;
printf("%d\n", *a);
return NULL;
}

int main()
{
int i, id[10];
pthread_t thread_tid[10];

for(i = 0; i < 10; i++) {
id[i] = i;
pthread_create(&thread_tid[i], NULL, collector, (void*)(id + i));
}

for(i = 0; i < 10; i++) {
pthread_join(thread_tid[i], NULL);
}

return 0;
}

有一个很好的 pthreads 介绍 here .

关于c - 通过 pthread_create 传递整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19602026/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com