55 "crypto/x509"
66 "io/ioutil"
77 "net"
8+ "sync"
89)
910
1011func ExampleCredential_x509Authentication () {
@@ -86,3 +87,50 @@ func ExampleCredential_x509Authentication() {
8687 // You should actually check the error code at each step.
8788 _ = err
8889}
90+
91+ func ExampleSession_concurrency () {
92+ // This example shows the best practise for concurrent use of a mgo session.
93+ //
94+ // Internally mgo maintains a connection pool, dialling new connections as
95+ // required.
96+ //
97+ // Some general suggestions:
98+ // - Define a struct holding the original session, database name and
99+ // collection name instead of passing them explicitly.
100+ // - Define an interface abstracting your data access instead of exposing
101+ // mgo to your application code directly.
102+ // - Limit concurrency at the application level, not with SetPoolLimit().
103+
104+ // This will be our concurrent worker
105+ var doStuff = func (wg * sync.WaitGroup , session * Session ) {
106+ defer wg .Done ()
107+
108+ // Copy the session - if needed this will dial a new connection which
109+ // can later be reused.
110+ //
111+ // Calling close returns the connection to the pool.
112+ conn := session .Copy ()
113+ defer conn .Close ()
114+
115+ // Do something(s) with the connection
116+ _ , _ = conn .DB ("" ).C ("my_data" ).Count ()
117+ }
118+
119+ ///////////////////////////////////////////////
120+
121+ // Dial a connection to Mongo - this creates the connection pool
122+ session , err := Dial ("localhost:40003/my_database" )
123+ if err != nil {
124+ panic (err )
125+ }
126+
127+ // Concurrently do things, passing the session to the worker
128+ wg := & sync.WaitGroup {}
129+ for i := 0 ; i < 10 ; i ++ {
130+ wg .Add (1 )
131+ go doStuff (wg , session )
132+ }
133+ wg .Wait ()
134+
135+ session .Close ()
136+ }
0 commit comments