@@ -19,6 +19,8 @@ import (
19
19
"net/url"
20
20
"os"
21
21
"strings"
22
+ "sync"
23
+ "sync/atomic"
22
24
"testing"
23
25
"time"
24
26
)
@@ -1220,40 +1222,59 @@ func TestConcurrent(t *testing.T) {
1220
1222
dbt .Fatalf ("%s" , err .Error ())
1221
1223
}
1222
1224
dbt .Logf ("Testing up to %d concurrent connections \r \n " , max )
1223
- canStop := false
1224
- c := make (chan struct {}, max )
1225
+
1226
+ var remaining , succeeded int32 = int32 (max ), 0
1227
+
1228
+ var wg sync.WaitGroup
1229
+ wg .Add (max )
1230
+
1231
+ var fatalError string
1232
+ var once sync.Once
1233
+ fatal := func (s string , vals ... interface {}) {
1234
+ once .Do (func () {
1235
+ fatalError = fmt .Sprintf (s , vals ... )
1236
+ })
1237
+ }
1238
+
1225
1239
for i := 0 ; i < max ; i ++ {
1226
1240
go func (id int ) {
1241
+ defer wg .Done ()
1242
+
1227
1243
tx , err := dbt .db .Begin ()
1244
+ atomic .AddInt32 (& remaining , - 1 )
1245
+
1228
1246
if err != nil {
1229
- canStop = true
1230
- if err .Error () == "Error 1040: Too many connections" {
1231
- max --
1232
- return
1233
- } else {
1234
- dbt .Fatalf ("Error on Con %d: %s" , id , err .Error ())
1247
+ if err .Error () != "Error 1040: Too many connections" {
1248
+ fatal ("Error on Conn %d: %s" , id , err .Error ())
1235
1249
}
1250
+ return
1236
1251
}
1237
- c <- struct {}{}
1238
- for ! canStop {
1239
- _ , err = tx . Exec ( "SELECT 1" )
1240
- if err != nil {
1241
- canStop = true
1242
- dbt . Fatalf ( "Error on Con %d: %s" , id , err . Error ())
1252
+
1253
+ // keep the connection busy until all connections are open
1254
+ for remaining > 0 {
1255
+ if _ , err = tx . Exec ( "DO 1" ); err != nil {
1256
+ fatal ( "Error on Conn %d: %s" , id , err . Error ())
1257
+ return
1243
1258
}
1244
1259
}
1245
- err = tx . Commit ()
1246
- if err != nil {
1247
- canStop = true
1248
- dbt . Fatalf ( "Error on Con %d: %s" , id , err . Error ())
1260
+
1261
+ if err = tx . Commit (); err != nil {
1262
+ fatal ( "Error on Conn %d: %s" , id , err . Error ())
1263
+ return
1249
1264
}
1265
+
1266
+ // everything went fine with this connection
1267
+ atomic .AddInt32 (& succeeded , 1 )
1250
1268
}(i )
1251
1269
}
1252
- for i := 0 ; i < max ; i ++ {
1253
- <- c
1270
+
1271
+ // wait until all conections are open
1272
+ wg .Wait ()
1273
+
1274
+ if fatalError != "" {
1275
+ dbt .Fatal (fatalError )
1254
1276
}
1255
- canStop = true
1256
1277
1257
- dbt .Logf ("Reached %d concurrent connections \r \n " , max )
1278
+ dbt .Logf ("Reached %d concurrent connections\r \n " , succeeded )
1258
1279
})
1259
1280
}
0 commit comments