Is there a built-in semaphore structure that allows for waiting on more than one resource?

谁说胖子不能爱 提交于 2019-12-02 08:46:08

You are presently using POSIX semaphores. They do not directly afford the possibility of atomically changing the semaphore value by more than one, except when creating a new semaphore.

System V semaphores (semget / semctl / semop) are generally considered inferior, but they do have some features that the POSIX flavor lacks, and this is one of them. Specifically, you can use semop() to atomically deduct any positive number from the semaphore's value, blocking until this can be done without reducing the value below zero.

But System V IPC is enough of a pain overall that I'd suggest instead setting up a shared variable representing the number of resources presently available, and using a mutex + condition variable instead of a semaphore. That would look something like this:

unsigned resources_available = ALL_RESOURCES;
pthread_mutex_t resource_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t resource_cv = PTHREAD_COND_INITIALIZER;

// ...

int acquire_resources(unsigned resources_wanted) {
    int result;

    // ...

    result = pthread_mutex_lock(resource_mutex);
    // handle errors ...
    while (resources_available < resources_wanted) {
        result = pthread_cond_wait(resource_cv, resource_mutex);
        // handle errors ...
    }
    resources_available -= resources_wanted;
    result = pthread_mutex_unlock(resource_mutex);
    // ...
}

int release_resources(unsigned resources_released) {
    int result;

    // ...

    result = pthread_mutex_lock(resource_mutex);
    // handle errors ...
    resources_available += resources_released;
    result = pthread_cond_broadcast(resource_cv);
    // handle errors ...
    result = pthread_mutex_unlock(resource_mutex);
    // ...
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!