Skip to content

Poor interaction with channels #1269

@sftse

Description

@sftse

We've been using rayon in a configuration with two thread pools connected by a channel, the first stage relying on some dynamic conditions to send tasks to the second thread pool. This always seemed a bit of a strange setup, so we attempted to refactor this to run on the same thread pool.

This minimal example shows how we tried to do this. By tweaking the constants it should be easy to achieve a deadlock, where no progression is visible.

use crossbeam_channel::Receiver;
use crossbeam_channel::SendError;
use crossbeam_channel::Sender;
use crossbeam_channel::TryRecvError;
use crossbeam_channel::TrySendError;
use rayon::ThreadPool;
use rayon::prelude::*;

const A: usize = 3;
const B: usize = 5;
const C: usize = 2;

struct Snd<'pool>(&'pool ThreadPool, Sender<()>);

fn bounded_channel<'pool>(
    pool: &'pool ThreadPool,
    capacity: usize,
) -> (Snd<'pool>, Recv<'pool>) {
    let (snd, rcv) = crossbeam_channel::bounded(capacity);
    (Snd(pool, snd), Recv(pool, rcv))
}

impl<'pool> Snd<'pool> {
    fn send(&self) -> Result<(), SendError<()>> {
        let mut t = ();
        while let Err(e) = self.1.try_send(t) {
            match e {
                TrySendError::Full(elt) => {
                    t = elt;
                    self.0.yield_now();
                }
                TrySendError::Disconnected(_) => return Err(SendError(())),
            }
        }
        Ok(())
    }
}

struct Recv<'pool>(&'pool ThreadPool, Receiver<()>);

impl Iterator for Recv<'_> {
    type Item = ();
    fn next(&mut self) -> Option<Self::Item> {
        self.try_recv()
    }
}

impl<'pool> Recv<'pool> {
    fn try_recv(&self) -> Option<()> {
        loop {
            match self.1.try_recv() {
                Ok(t) => return Some(t),
                Err(TryRecvError::Empty) => {
                    self.0.yield_now();
                }
                Err(TryRecvError::Disconnected) => return None,
            };
        }
    }
}

fn foo(snd: Snd<'_>) {
    [(); A]
        .par_iter()
        .for_each(|_| {
            for _ in 0..B {
                snd.send().unwrap();
            }
        })
}

fn main() {
    let pool = rayon::ThreadPoolBuilder::new().build().unwrap();
    let (snd, rcv) = bounded_channel(&pool, C);
    pool.join(
        || foo(snd),
        || rcv.par_bridge().for_each(|()| {}),
    );
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions