通过 pthread_create 传递整数值 [英] Pass integer value through pthread_create

查看:69
本文介绍了通过 pthread_create 传递整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I simply want to pass the value of an integer to a thread.

我该怎么做?

我试过了:

    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 强制转换为 void 指针,编译器会报错:

The compiler will complain if you don't cast i to a void pointer:

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

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

That said, casting an integer to a pointer isn't strictly safe:

ISO/IEC 9899:201x6.3.2.3 指针

ISO/IEC 9899:201x 6.3.2.3 Pointers

  1. 整数可以转换为任何指针类型.除了前面指定的,结果是实现定义的,可能没有正确对齐,可能不指向引用类型的实体,并且可能是陷阱表示.

所以你最好向每个线程传递一个单独的指针.

so you're better off passing a separate pointer to each thread.

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

Here's a full working example, which passes each thread a pointer to a separate element in an array:

#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;
}

此处有一个很好的 pthread 介绍.

There's a nice intro to pthreads here.

这篇关于通过 pthread_create 传递整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆