Channels provide a safe way for concurrent goroutines to communicate with each other in Soul. They allow you to send and receive values between different parts of your concurrent program, preventing race conditions and ensuring thread-safe data sharing.
Receive values from channels using the <- operator or the receive() method:
Copy
Ask AI
ch = Concurrency.createChannel()// Send a value in another goroutineConcurrency.run(soul() { ch <- "message from goroutine"})// Receive using arrow syntaxmessage = <-chprintln("Received: " + message)// Receive using method syntaxvalue = ch.receive()println("Received: " + value)
Select statements allow you to work with multiple channel operations:
Copy
Ask AI
ch1 = Concurrency.createChannel()ch2 = Concurrency.createChannel()// Send to channels in separate goroutinesConcurrency.run(soul() { Concurrency.sleep(100) ch1 <- "from channel 1"})Concurrency.run(soul() { Concurrency.sleep(200) ch2 <- "from channel 2"})// Wait for the first available channelselect { case msg1 = <-ch1: println("Received from ch1: " + msg1) case msg2 = <-ch2: println("Received from ch2: " + msg2)}
ch = Concurrency.createChannel()timeout = Concurrency.createChannel()// Set up timeoutConcurrency.run(soul() { Concurrency.sleep(1000) // 1 second timeout timeout <- true})// Wait for either data or timeoutselect { case data = <-ch: println("Received data: " + data) case <-timeout: println("Operation timed out")}