通过pthread_create传递整数值

时间:2013-10-26 02:01:58

标签: c pthreads

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

我该怎么做?

我试过了:

    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]

4 个答案:

答案 0 :(得分:6)

如果你没有将i转换为void指针,编译器会抱怨:

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

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

  

ISO / IEC 9899:201x   6.3.2.3指针

     
      
  1. 整数可以转换为任何指针类型。除非先前指定,否则结果是实现定义的,可能未正确对齐,可能不指向引用类型的实体,并且可能是陷阱表示。
  2.   

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

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

#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有一个很好的介绍。

答案 1 :(得分:1)

❯ echo xxx >! xxx
❯ alias -g SP='| sponge '
❯ cat xxx SP xxx
❯ cat xxx
(empty file, no lines are shown here)

答案 2 :(得分:0)

int是32位,而64位Linux中的void *是64位;在这种情况下,您应该使用long int而不是int;

long int i;
pthread_create(&thread_id, NULL, fun, (void*)i);

int fun(void * i)function

 long int id = (long int) i;

答案 3 :(得分:0)

最好使用struct在一个中发送更多参数:

struct PARAMS
{
    int i;
    char c[255];
    float f;
} params;

pthread_create(&thread_id, NULL, fun, (void*)(&params));

然后您可以cast paramsPARAMS*并在pthread routine中使用它:

PARAMS *p = static_cast<PARAMS*>(params);
p->i = 5;
strcpy(p->c, "hello");
p->f = 45.2;
相关问题