[Programming]Multiple Producer Single Consumer (MPSC)

General

# What is MPSC?

multiple entities (producers) generate or produce data, and a single entity (consumer) processes or consumes that data. This pattern is often employed in concurrent or parallel computing environments to efficiently handle data production and consumption.

# Rust example

The following example won't compile because it is trying to pass `receiver` to multiple `Worker` instance.

```Rust

let (sender, receiver) = mpsc::channel();

let mut workers = Vec::with_capacity(size);
// The following code is trying to pass `receiver` to multiple `Worker` instance.
for id in 0..size {
    workers.push(Worker::new(id, receiver));
}

ThreadPool {workers, sender}

```

I will get scoled from compiler like that.

To share ownership across multiple threads and allow the threads to mutate the value, we need to use Arc<Mutex<T>>. The Arc type will let multiple workers own the receiver, and Mutex will ensure that only one worker gets a job from the receiver at a time.

```Rust

assert!(size > 0);

let (sender, receiver) = mpsc::channel();

let receiver = Arc::new(Mutex::new(receiver));

let mut workers = Vec::with_capacity(size);

for id in 0..size {
    workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { workers, sender }

```

----

references

Turning Our Single-Threaded Server into a Multithreaded Server - The Rust Programming Language

コメント

タイトルとURLをコピーしました