简体   繁体   中英

Can I reach C semaphore value ? (sem_t)

To enter into if, I need to reach the value in "t" variable. Is there any way I can do this?

int main(int argc , char* argv[]){

    sem_t t;
    sem_init(&t, 0 /*#ofP*/, 1/*Semaphore start value*/);

    if(t > 0){

        printf("Hello");
    }

    return 0;
}

You can use sem_getvalue (error checking omitted for brevity):

sem_t t;
sem_init (&t, 0 /*#ofP*/, 1 /*Semaphore start value*/);

int sval;
sem_getvalue (&t, &sval);
if (sval > 0)
    printf ("Hello");

However: semaphores are generally used in a multi tasking / multi threaded context, so the value can change from underneath you at any time. If your goal is to wait on the semaphore until it is signalled, use sem_wait (or sem_trywait or sem_timedwait ) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM