简体   繁体   中英

Simple Multi-threading Stack Implementation using Conditional Variables

In our CS course we used POSIX Thread Programming to implement a simple stack data structure. We therefore made use of pthread_cond_wait and pthread_cond_signal :

pthread_mutex_t write_mutex; 
pthread_mutex_t read_mutex; 

pthread_cond_t write_cond; 
pthread_cond_t read_cond;

int read()
{
    pthread_mutex_lock(&read_mutex); 
    while(is_empty())
    {
        pthred_cond_wait(&read_cond, &read_mutex);
    }
    // read value [...]
    pthread_cond_signal(&write_cond);
    pthread_mutex_unlock(&read_mutex);

    return read_value;

}

The write function is implemented similarly but locking the write_mutex and signaling the read_cond instead.

Q: My problem with this implementation is: Doesn't this require a 1:1 ratio between readings a writings due to the signaling? This implementation does not allow to write multiple items without any reads in between since every write requires a signal triggered in the read function (vice versa multiple reads).

Is my understanding correct or am I missing something?

Q2 How long is a signal "valid" after calling pthread_cond_signal(...) ?

Q : My problem with this implementation is: Doesn't this require a 1:1 ratio between readings a writings due to the signaling? This implementation does not allow to write multiple items without any reads in between since every write requires a signal triggered in the read function (vice versa multiple reads).

If the write() function is truly analogous to the read() function presented, then yes and no. I think you're suggesting that the stack could never have more than one element, but that in particular is not so. Note how a thread entering your read() function and finding the stack nonempty will bypass waiting on the condition variable altogether. A thread waits to read only if the stack is empty. The analog on the other side would be that threads wait to write only if the stack is full to capacity.

Q2 How long is a signal "valid" after calling pthread_cond_signal(...)?

No time at all. Only threads already waiting on a condition variable can be unblocked when that CV is signaled. There is not afterward any memory of a signal having been received, even if no thread was unblocked by it.

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