aboutsummaryrefslogtreecommitdiffstats
path: root/exercises/concurrent/concurrent1/main_test.go
blob: 396511330b233cbcda61a1faf133230442dba221 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// concurrent1
// Make the tests pass!

// I AM NOT DONE
package main_test

import (
	"bytes"
	"fmt"
	"sync"
	"testing"
)

func TestPrinter(t *testing.T) {
	var buf bytes.Buffer
	print(&buf)

	out := buf.String()

	for i := 0; i < 3; i++ {
		want := fmt.Sprintf("Hello from goroutine %d!", i)
		if !bytes.Contains([]byte(out), []byte(want)) {
			t.Errorf("Output did not contain expected string. Wanted: %q, Got: %q", want, out)
		}
	}
}

func print(buf *bytes.Buffer) {
	var wg sync.WaitGroup
	var mu sync.Mutex

	goroutines := 3

	for i := 0; i < goroutines; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			mu.Lock()
			//fmt.Fprintf(buf, "Hello from goroutine %d!\n", i)
			mu.Unlock()
		}(i)
	}

	wg.Wait()
}