使用条件变量的简单多线程堆栈实现

Simple Multi-threading Stack Implementation using Conditional Variables

在我们的 CS 课程中,我们使用 POSIX 线程编程来实现 一个简单的堆栈数据结构。因此我们使用了 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;

}

写函数的实现方式类似,但锁定 write_mutex 并向 read_cond 发送信号。

问: 我对这个实现的问题是:由于信号,这不需要 1:1 读取和写入之间的比率吗?此实现不允许在中间没有任何读取的情况下写入多个项目,因为每次写入都需要在读取函数中触发一个信号(反之亦然)。

我的理解是否正确,还是我遗漏了什么?

Q2调用pthread_cond_signal(...)后信号"valid"多长时间?

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).

如果 write() 函数确实类似于所提供的 read() 函数,那么是和否。我认为您是在暗示堆栈中的元素永远不会超过一个,但事实并非如此。请注意一个线程如何进入您的 read() 函数并发现堆栈非空将完全绕过对条件变量的等待。只有当堆栈为空时,线程才会等待读取。另一方面的模拟是线程只有在堆栈已满时才等待写入。

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

没时间。当发出 CV 信号时,只有已经在等待条件变量的线程才能解除阻塞。之后没有任何关于收到信号的记忆,即使没有线程被它解除阻塞。