Note that there are some explanatory texts on larger screens.

plurals
  1. POasync reply in registry pattern
    text
    copied!<p>I'm learning go, and I would like to explore some patterns.</p> <p>I would like to build a Registry component which maintains a map of some stuff, and I want to provide a serialized access to it:</p> <p>Currently I ended up with something like this:</p> <pre><code>type JobRegistry struct { submission chan JobRegistrySubmitRequest listing chan JobRegistryListRequest } type JobRegistrySubmitRequest struct { request JobSubmissionRequest response chan Job } type JobRegistryListRequest struct { response chan []Job } func NewJobRegistry() (this *JobRegistry) { this = &amp;JobRegistry{make(chan JobRegistrySubmitRequest, 10), make(chan JobRegistryListRequest, 10)} go func() { jobMap := make(map[string] Job) for { select { case sub := &lt;- this.submission: job := MakeJob(sub.request) // .... jobMap[job.Id] = job sub.response &lt;- job.Id case list := &lt;- this.listing: res := make([]Job, 0, 100) for _, v := range jobMap { res = append(res, v) } list.response &lt;- res } /// case somechannel.... } }() return } </code></pre> <p>Basically, I encapsulate each operation inside a struct, which carries the parameters and a response channel.</p> <p>Then I created helper methods for end users:</p> <pre><code>func (this *JobRegistry) List() ([]Job, os.Error) { res := make(chan []Job, 1) req := JobRegistryListRequest{res} this.listing &lt;- req return &lt;-res, nil // todo: handle errors like timeouts } </code></pre> <p>I decided to use a channel for each type of request in order to be type safe.</p> <hr> <p>The problem I see with this approach are:</p> <ul> <li><p>A lot of boilerplate code and a lot of places to modify when some param/return type changes</p></li> <li><p>Have to do weird things like create yet another wrapper struct in order to return errors from within the handler goroutine. (If I understood correctly there are no tuples, and no way to send multiple values in a channel, like multi-valued returns)</p></li> </ul> <p>So, I'm wondering whether all this makes sense, or rather just get back to good old locks.</p> <p>I'm sure that somebody will find some clever way out using channels.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload