在我们的 CS 类(class)中,我们使用 POSIX 线程编程来实现
一个简单的堆栈数据结构。因此,我们使用了 pthread_cond_wait
和 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 函数的实现方式类似,但锁定 write_mutex
并向 read_cond
发出信号。
问: 我对这个实现的问题是:由于信号的原因,这是否需要读取和写入之间的 1:1 比率?此实现不允许在中间没有任何读取的情况下写入多个项目,因为每次写入都需要在读取函数中触发一个信号(反之亦然)。
我的理解正确还是我遗漏了什么?
Q2调用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).
如果 write()
函数确实类似于所提供的 read()
函数,那么是和否。我认为您是在暗示堆栈中的元素永远不会超过一个,但事实并非如此。请注意一个线程如何进入您的 read()
函数并发现堆栈非空将完全绕过对条件变量的等待。只有当堆栈为空时,线程才会等待读取。另一方面的模拟是只有当堆栈已满时,线程才会等待写入。
Q2 How long is a signal "valid" after calling pthread_cond_signal(...)?
没时间。当发出 CV 信号时,只有已经在等待条件变量的线程才能解除阻塞。之后没有任何关于收到信号的内存,即使没有线程被它解除阻塞。
关于c - 使用条件变量的简单多线程堆栈实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55139234/