hey, I found this code can't stop, it is stuck. ho...
# coroutines
k
hey, I found this code can't stop, it is stuck. how can I fix it ?
Copy code
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val channel1 = Channel<Int>(0)
    val channel2 = Channel<Int>(0)
    val channel3 = Channel<Int>(0)

    val n = 5

    val job1 = launch {
        for (i in 1..n) {
            channel1.receive()
            print("0")

            if (i % 2 == 0) {
                channel2.send(1)
            } else {
                channel3.send(1)
            }
        }

        channel2.send(1)
        channel3.send(1)
    }

    val job2 = launch {
        for (i in 2..n step 2) {
            channel2.receive()
            print(i)
            channel1.send(1)
        }
    }

    val job3 = launch {
        for (i in 1..n step 2) {
            channel3.receive()
            print(i)
            channel1.send(1)
        }
    }

    channel1.send(1)

    joinAll(job1, job2, job3)
}
e
it won't if you use
Channel(capacity = 1)
you're sending 1 more element to every channel than you are receiving
k
thank you, that works well, but why in other language is ok when the channel size is 0 ?
Copy code
fn main() {
    let n = 5;
    let (tx1, rx1) = crossbeam_channel::bounded(0);
    let (tx2, rx2) = crossbeam_channel::bounded(0);
    let (tx3, rx3) = crossbeam_channel::bounded(0);
    
        
    let job1: JoinHandle<anyhow::Result<()>> = thread::spawn(move || {
        for i in 1..=n {
            rx1.recv()?;
            print!("0");

            if i % 2 == 0 {
                tx2.send(1)?;
            } else {
                tx3.send(1)?;
            }
        }

        Ok(())
    });

    let tx1_1 = tx1.clone();
    
    let job2: JoinHandle<anyhow::Result<()>> = thread::spawn(move || {
        for i in (2..=n).step_by(2) {
            rx2.recv()?;
            print!("{}", i);
            tx1_1.send(1)?;
        }

        Ok(())
    });

    let tx1_2 = tx1.clone();
    let job3: JoinHandle<anyhow::Result<()>> = thread::spawn(move || {
        for i in (1..=n).step_by(2) {
            rx3.recv()?;
            print!("{}", i);
            tx1_2.send(1)?;
        }

        Ok(())
    });

    tx1.send(1).unwrap();

    job1.join();
    job2.join();
    job3.join();

}
tachikema kun ?
e
because the final send in Rust is actually failing, you're just ignoring the failure
replace those
?
with
.unwrap()
and you'll see that it panics
k
thanks, I see that error