将全局变量作为参数传递给方法

Pass a global variable to a method as an argument

提问人:AssSoonAsPossiblee 提问时间:12/1/2021 最后编辑:AssSoonAsPossiblee 更新时间:12/1/2021 访问量:47

问:

全局变量:

int REGISTRATION_SIZE = 10;

我想将一个全局变量(REGISTRATION_SIZE)作为方法参数传递给wait_for_avaliable方法,例如wait_for_avaliable(int size)。我怎样才能做到这一点?

void wait_for_available_resource(struct Patient *p, pthread_mutex_t *registration_mutex, pthread_cond_t *register_cond){
    int rnd_wait_time;
    pthread_mutex_lock(registration_mutex);
    while(REGISTRATION_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);
    }
    REGISTRATION_SIZE--;
    printf("Registration size:%d\n",REGISTRATION_SIZE);
    pthread_mutex_unlock(registration_mutex);
    
}

我尝试过这种方式,但它不起作用:

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);
    
}
C 全局变量 按引用 传递指针

评论

0赞 dbush 12/1/2021
定义“不起作用”
0赞 AssSoonAsPossiblee 12/1/2021
我无法获得相同的输出
0赞 the busybee 12/1/2021
由于是指向要使用的值的指针,因此需要正确使用它。使用而不是取消引用指针。请将编译器的警告级别提高到最大值并更正代码,直到所有警告和错误都消失。size*sizesize

答: 暂无答案