内螺纹打印参数 [英] Print arguments inside thread

查看:118
本文介绍了内螺纹打印参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 无效* consumer_child(无效*参数){
    范围RNG = *((范围*)参数);
    //使用很容易地确定每个线程的范围prinnting
    的printf(consumer_child [%D-%D]。开始的\\ n,rng.start,rng.end);    了pthread_exit(0);
}

当我打印出来,它打印内存位置,而不是价值。我需要打印的价值。

在主线程中开始和结束的值是否设置正确。我检查了他们。

在主我设置参数如下

 范围* RNG =的malloc(sizeof的(* RNG));
        RNG-GT&;启动= I * numbersPerChild;
        RNG->端=(numbersPerChild *第(i + 1))-1;
        的printf(范围线程%d为%d到%d \\ n,我,RNG-GT&;启动,RNG-GT&端);
        的printf(测试打印%d个\\ N,RNG-GT&;启动);
在pthread_create(安培; TID [Ⅰ],NULL,consumer_child,(无效*)及RNG);

范围是一个结构

  typedef结构
{
    INT开始;
    INT结束;
} 范围;


解决方案

您需要修改:

 在pthread_create(安培; TID [I],NULL,consumer_child,(无效*)及RNG);

 在pthread_create(安培; TID [I],NULL,consumer_child,RNG);

因为 RNG 已经是一个指针,你想传递的,而不是它的地址。你并不需要一个对象指针转换为无效* 在C,除非你有期望一个可变参数函数之一,你想传递一种不同的对象的指针。

void * consumer_child(void *arguments){
    Range rng = *((Range *) arguments);
    //prinnting with the range to easily identify each thread
    printf("consumer_child[%d-%d] started\n", rng.start, rng.end );

    pthread_exit(0);
}

When I print it, it prints memory location, not the value. I need to print the value.

In main thread start and end values are set properly. I have checked them.

in main I have set the argument as following

Range *rng = malloc(sizeof(*rng));
        rng->start = i * numbersPerChild;
        rng->end = (numbersPerChild * (i + 1)) -1 ;
        printf("Range for thread %d is %d to %d\n", i, rng->start, rng->end );
        printf("test print %d\n",rng->start);
pthread_create(&tid[i], NULL, consumer_child, (void *)&rng );

Range is a struct

typedef struct
{
    int start;
    int end;
} Range;

解决方案

You need to change:

pthread_create(&tid[i], NULL, consumer_child, (void *)&rng );

to:

pthread_create(&tid[i], NULL, consumer_child, rng);

since rng is already a pointer, and you want to pass that, not its address. You don't need to cast an object pointer to void * in C, unless you have a variadic function that expects one and you're trying to pass it a different kind of object pointer.

这篇关于内螺纹打印参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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