【问题标题】:Print arguments inside thread在线程内打印参数
【发布时间】:2015-04-20 03:01:03
【问题描述】:
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);
}

当我打印它时,它会打印内存位置,而不是值。我需要打印值。

在主线程中正确设置了开始和结束值。我已经检查过了。

在main中我将参数设置如下

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 );

范围是一个结构

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

【问题讨论】:

  • 什么是范围?你是如何创建线程的?
  • (void *)&rng 更改为rng
  • @CoolGuy 我添加了更多代码,请检查。

标签: c multithreading


【解决方案1】:

你需要改变:

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

到:

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

因为rng 已经是一个指针,你想传递它,而不是它的地址。您不需要在 C 中将对象指针强制转换为 void *,除非您有一个期望一个可变参数函数并且您正试图向它传递一种不同类型的对象指针。

【讨论】:

    猜你喜欢
    • 2021-10-17
    • 1970-01-01
    • 2015-01-20
    • 2017-11-22
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    相关资源
    最近更新 更多