Amqp: Question: Is it safe to share channels/connections across goroutines?

Created on 2 Oct 2013  路  4Comments  路  Source: streadway/amqp

Most helpful comment

@michaelklishin the interleaving of frames from different threads on the same channel is a concern for most library implementations. This library serializes sends until all frames are delivered whether it's a method with content or not.

This is the mutex: https://github.com/streadway/amqp/blob/master/channel.go#L206 that ensures all frames for a publishing are written before the next send is begun per channel.

This test uses multiple goroutines to deliver a payload that would need to be split across multiple body frames over the same channel: https://github.com/streadway/amqp/blob/master/client_test.go#L466

All 4 comments

The types in this library are designed to be safe to used from multiple goroutines, though it's generally simpler to keep a single goroutine that manages the IO to the broker and communicate into or out of your AMQP logic with a chan in a type relevant to your application.

Thanks for the answer.

@cenkalti publishing from multiple goroutines on the same channel is not safe.
To be more specific: every time you publish a non-empty message,
the client sends 3 (or more) frames on the wire:

[method: basic.publish] [content headers] [content body]+

When publishing on the same channel from multiple threads/goroutines/processes,
you may end up with incorrect interleaving, e.g.

[method: basic.publish] [content headers] [method: basic.publish] [content body] [content headers] [content body]

RabbitMQ won't be able to parse this frame sequence and raises a fatal error. The solution
is to either

  • Avoid publishing on _the same_ channel from multiple threads/goroutines/processes
  • Synchronize publishing in your own code

@michaelklishin the interleaving of frames from different threads on the same channel is a concern for most library implementations. This library serializes sends until all frames are delivered whether it's a method with content or not.

This is the mutex: https://github.com/streadway/amqp/blob/master/channel.go#L206 that ensures all frames for a publishing are written before the next send is begun per channel.

This test uses multiple goroutines to deliver a payload that would need to be split across multiple body frames over the same channel: https://github.com/streadway/amqp/blob/master/client_test.go#L466

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fho picture fho  路  7Comments

michaeljs1990 picture michaeljs1990  路  11Comments

eimugray picture eimugray  路  12Comments

kamal-github picture kamal-github  路  9Comments

vibridi picture vibridi  路  7Comments