【发布时间】:2020-09-29 21:36:54
【问题描述】:
我想在 Rust 中构建一个单生产者多消费者示例,其中生产者的未完成项不得超过 10 个。我在 C 中建模了一个使用互斥锁和两个 condvar 的解决方案。一个 condvar 是在没有东西可消费时等待消费者,一个 condvar 是在未消费项目数大于 10 时等待生产者。C 代码如下。
据我从 Rust 文档中了解到,std::sync::Mutex 和 std::sync::Condvar 之间必须存在 1-1 连接,因此我无法准确翻译我的 C 解决方案。
是否有其他方法可以使用std::sync::Mutex 和std::sync::Condvar 在 Rust 中实现相同的目的(我看不到)。
#define _GNU_SOURCE
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
//
// This is a simple example of using a mutex and 2 condition variables to
// sync a single writer and multiple readers interacting with a bounded (fixed max size) queue
//
// in this toy example a queue is simulated by an int counter n_resource
//
int n_resource;
pthread_cond_t rdr_cvar;
pthread_cond_t wrtr_cvar;
pthread_mutex_t mutex;
void reader(void* data)
{
long id = (long)data;
for(;;) {
pthread_mutex_lock(&mutex);
while (n_resource <= 0) {
pthread_cond_wait(&rdr_cvar, &mutex);
}
printf("Reader %ld n_resource = %d\n", id, n_resource);
--n_resource;
// if there are still things to read - singla one reader
if(n_resource > 0) {
pthread_cond_signal(&rdr_cvar);
}
// if there is space for the writer to add another signal the writer
if(n_resource < 10) {
pthread_cond_signal(&wrtr_cvar);
}
pthread_mutex_unlock(&mutex);
}
}
void writer(void* data)
{
for(;;) {
pthread_mutex_lock(&mutex);
printf("Writer before while n_resource %d \n", n_resource);
while (n_resource > 10) {
pthread_cond_wait(&wrtr_cvar, &mutex);
}
printf("Writer after while n_resource %d \n", n_resource);
++n_resource;
// if there is something for a reader to read signal one of the readers.
if(n_resource > 0) {
pthread_cond_signal(&rdr_cvar);
}
pthread_mutex_unlock(&mutex);
}
}
int main()
{
pthread_t rdr_thread_1;
pthread_t rdr_thread_2;
pthread_t wrtr_thread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&rdr_cvar, NULL);
pthread_cond_init(&wrtr_cvar, NULL);
pthread_create(&rdr_thread_1, NULL, &reader, (void*)1L);
pthread_create(&rdr_thread_2, NULL, &reader, (void*)2L);
pthread_create(&wrtr_thread, NULL, &writer, NULL);
pthread_join(wrtr_thread, NULL);
pthread_join(rdr_thread_1, NULL);
pthread_join(rdr_thread_2, NULL);
}
【问题讨论】:
-
看起来您的问题可能会被Buffer in Rust with Mutex and Condvar 的答案所回答,这表明使用两个
Condvars 和一个Mutex。如果没有,请edit您的问题解释差异。否则,我们可以将此问题标记为已回答。
标签: rust mutex condition-variable