| 13 | ) |
| 14 | |
| 15 | func TestReusableGoroutinesPool(t *testing.T) { |
| 16 | buf := make([]byte, 1<<20) |
| 17 | buf = buf[:runtime.Stack(buf, false)] |
| 18 | testGoroutine := regexp.MustCompile(`goroutine (\d+) \[running\]:`).FindSubmatch(buf)[1] |
| 19 | require.NotEmpty(t, testGoroutine, "test goroutine not found") |
| 20 | |
| 21 | countGoroutines := func() int { |
| 22 | buf := make([]byte, 1<<20) |
| 23 | buf = buf[:runtime.Stack(buf, true)] |
| 24 | // Count the number of goroutines created by this test |
| 25 | // This ensures that the test isn't affected by leaked goroutines from other tests. |
| 26 | return strings.Count(string(buf), " in goroutine "+string(testGoroutine)) |
| 27 | } |
| 28 | |
| 29 | const workerCount = 2 |
| 30 | w := NewReusableGoroutinesPool(workerCount) |
| 31 | require.Equal(t, 0, countGoroutines()) |
| 32 | |
| 33 | // Wait a little bit so both goroutines would be waiting on the jobs chan. |
| 34 | time.Sleep(10 * time.Millisecond) |
| 35 | |
| 36 | ch := make(chan struct{}) |
| 37 | w.Go(func() { <-ch }) |
| 38 | require.Equal(t, 1, countGoroutines()) |
| 39 | w.Go(func() { <-ch }) |
| 40 | require.Equal(t, workerCount, countGoroutines()) |
| 41 | w.Go(func() { <-ch }) |
| 42 | require.Equal(t, workerCount+1, countGoroutines()) |
| 43 | |
| 44 | // end workloads, we should have only the workers again. |
| 45 | close(ch) |
| 46 | for i := 0; i < 1000 && countGoroutines() >= workerCount; i++ { |
| 47 | time.Sleep(time.Millisecond) |
| 48 | } |
| 49 | require.Equal(t, workerCount, countGoroutines()) |
| 50 | |
| 51 | // close the workers, eventually they should be gone. |
| 52 | w.Close() |
| 53 | for i := 0; i < 1000; i++ { |
| 54 | if countGoroutines() == 0 { |
| 55 | return |
| 56 | } |
| 57 | time.Sleep(time.Millisecond) |
| 58 | } |
| 59 | t.Fatalf("expected %d goroutines after closing, got %d", 0, countGoroutines()) |
| 60 | } |
| 61 | |
| 62 | // TestReusableGoroutinesPool_Race tests that Close() and Go() can be called concurrently. |
| 63 | func TestReusableGoroutinesPool_Race(t *testing.T) { |