You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将全局变量REGISTRATION_SIZE作为参数传入wait_for_available_resource函数

错误原因

你的实现问题出在对指针参数的操作逻辑错误,所有对size的操作都没有正确解引用,实际操作的是指针本身的内存地址,而非指针指向的全局变量值:

  • 循环条件while(size == 0)是判断指针地址是否为0,而非判断指向的可用数量是否为0
  • 递减操作size--是让指针地址向后偏移1个int类型长度,而非修改指向的可用数量
  • 打印语句直接输出size,打印的是指针的内存地址而非可用数量值

正确修改后的代码

void wait_for_available_resource(struct Patient *p, pthread_mutex_t *registration_mutex, pthread_cond_t *register_cond, int *size){
    int rnd_wait_time;
    pthread_mutex_lock(registration_mutex);
    // 解引用获取指向的数值
    while(*size == 0){
        rnd_wait_time = generate_rnd_numb(WAIT_TIME) + 1;
        printf("Patient[%d] is waiting for an availabe desk.\n",p->thread_num);
        sleepForMs(rnd_wait_time);
        increase_meters(p);
        checkForRestOrCafe(p);
        pthread_cond_wait(register_cond,registration_mutex);
    }
    // 加括号保证先解引用再做递减操作
    (*size)--;
    // 解引用输出实际数值
    printf("Registration size:%d\n",*size);
    pthread_mutex_unlock(registration_mutex);
}

调用方式

调用函数时传入全局变量的地址即可:

wait_for_available_resource(p, registration_mutex, register_cond, &REGISTRATION_SIZE);

内容的提问来源于stack exchange,提问作者AssSoonAsPossiblee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:15:07