Goroutines are lightweight threads of execution. Channels are typed conduits for safe communication and synchronization between goroutines. Together, they enable concurrent processing without explicit locks or condition variables.
- https://gobyexample.com/goroutines
- https://gobyexample.com/channels
- https://go.dev/tour/concurrency/1
Implement a basic concurrent request-response flow where a "Client" sends a request to a "Server" running in a separate goroutine, and waits for the response via a channel.
- Function:
SendRequest(input string) string - Create an unbuffered string channel.
- Start the
Serverfunction in a new goroutine (go Server(...)), passing the input and the channel. - Block and wait for the response from the channel.
- Return the received response.
- Function:
Server(request string, response chan string) - Runs concurrently (invoked with
go). - Format the output string as
"processed: <request>". - Send the formatted string into the
responsechannel. - Do not close the channel.
input: The raw request string (e.g., "ping").
- Returns the processed string (e.g., "processed: ping").
SendRequest("hello")- Channel created.
go Server("hello", ch)starts.SendRequestblocks on<-ch.Serversends"processed: hello".SendRequestunblocks and returns"processed: hello".
To run the tests, execute the following command from the root directory:
go test -v ./quests/015.go_routineOr from the quest directory:
go test -vExpected output:
=== RUN TestSendRequest
--- PASS: TestSendRequest (0.00s)
PASS