c - 如何安排 pthread_cond_signal() 以使其始终跟随另一个线程上的 pthread_cond_wait()?

标签 c multithreading pthreads

我正在测试生产者-消费者场景,其中生产者在尝试写入已满队列时会阻塞。我想测试生产者线程是否正确唤醒并在消费者从完整队列中读取后按预期工作*。队列写入 API 在检测到队列已满时调用 pthread_cond_wait(),读取 API 在从队列中读取后向条件变量发出信号。

如何确保在我的测试环境中发生Sequence 3而不是任何其他操作序列?

enter image description here

* 是的,我想单独测试这个有限的场景;还有其他测试可以测试整个队列的功能,此测试是对这些测试的补充。

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/

相关文章:

haskell - Windows 10 上的 ghci 错误 : user specified . o/.so/.DLL 无法加载(addDLL: pthread

c - 从文本文件加载缓冲区后的长间距

c# - C#/.NET 4.0+ 实现可取消后台线程的方法是什么?

c++ - pthread_mutex 锁是否比用户在代码中强加的内存屏障提供更高的性能

c# - 在 C# 中使用线程构建分布式 DFS

c++ - 在非 boost 线程中使用 boost::thread_specific_ptr

c - pthreads中pthread_t的数据类型?

将一个结构指针转换为另一个 - C

c - 我试图终止使用 fgets() 函数的 while() 循环

c - 编译时显示警告 :cannot find entry symbol Rrors;defaulting to 0000000000400590