我正在测试生产者-消费者场景,其中生产者在尝试写入已满队列时会阻塞。我想测试生产者线程是否正确唤醒并在消费者从完整队列中读取后按预期工作*。队列写入 API 在检测到队列已满时调用 pthread_cond_wait(),读取 API 在从队列中读取后向条件变量发出信号。
如何确保在我的测试环境中发生Sequence 3而不是任何其他操作序列?
* 是的,我想单独测试这个有限的场景;还有其他测试可以测试整个队列的功能,此测试是对这些测试的补充。
More details -
There is a single mutex governing the queue. There are 2 conditional variables - one to signal write (all writes), one to signal read (all reads). The queue_write API blocks on the read condvar if the queue is full. The queue_read API blocks on the write condvar if the queue is empty. All signalling happens under the aegis of the mutex.
There is a lot more nuance in the queue but for the purpose of setting context for this question this is an adequate summary of the queue's functioning.
最佳答案
由于您的队列使用 pthread_cond_signal
,因此它也必须持有锁。所以你的测试用例应该简单地持有锁,创建生产者,然后等待信号。生产者产生信号后,释放锁,创建消费者。
void test () {
pthread_mutex_lock(q_lock);
// Blocks on the same queue lock the producer and
// consumer would use.
create_producer();
// The producer will block on the queue lock when
// it tries to write to the queue.
do {
pthread_cond_wait(q_write_cond, q_lock);
// Mimic a blocked queue_read, and wait for the
// producer to signal. This will release the lock
// and allow the producer to progress.
} while (!q_is_full());
// The queue is now full, lock is held since
// pthread_cond_wait returned.
pthread_mutex_unlock(q_lock);
// Release the queue lock, allow the consumer to
// operate unhindered.
create_consumer();
// The consumer will proceed to drain the queue.
}
关于c - 如何安排 pthread_cond_signal() 以使其始终跟随另一个线程上的 pthread_cond_wait()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34763941/