Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are a few things you should fix.</p> <ul> <li><p>The methods on the Queue type should have pointer receivers. Otherwise, every method call will create a copy of the current queue type and any changes to queue fields will not persist beyond the method call itself.</p></li> <li><p>Waiting for all routines to finish, can be done using a <code>sync.WaitGroup</code>. This is specifically what it was designed for.</p></li> <li><p>Maintaining a thread-safe push/pop counter inside the queue type can be done by using the <code>sync/atomic</code> package.</p></li> </ul> <p>As far as speed goes, from your example, I am not quite sure what you are trying to achieve. Any optimizations might come up if you elaborate on that a little.</p> <p>Here is an example I modified from your code:</p> <pre><code>package main import ( "log" "runtime" "sync" "sync/atomic" "time" ) const SizePerThread = 10000000 type Queue struct { records string count int64 } func (q *Queue) push(record chan interface{}) { record &lt;- time.Now() newcount := atomic.AddInt64(&amp;q.count, 1) log.Printf("Push: %d", newcount) } func (q *Queue) pop(record chan interface{}) { &lt;-record newcount := atomic.AddInt64(&amp;q.count, -1) log.Printf("Pop: %d", newcount) } func main() { var wg sync.WaitGroup runtime.GOMAXPROCS(runtime.NumCPU()) record := make(chan interface{}, 1000000) queue := new(Queue) // We are launching 20 goroutines. // Let the waitgroup know it should wait for as many // of them to finish. wg.Add(20) for i := 0; i &lt; 10; i++ { go func() { defer wg.Done() for j := 0; j &lt; SizePerThread; j++ { queue.push(record) } }() go func() { defer wg.Done() for j := 0; j &lt; SizePerThread; j++ { queue.pop(record) } }() } // Wait for all goroutines to finish. wg.Wait() } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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