uitable: added concurrency safety
Greg Osuri
8 years ago
3 | 3 |
import (
|
4 | 4 |
"fmt"
|
5 | 5 |
"strings"
|
|
6 |
"sync"
|
6 | 7 |
|
7 | 8 |
"github.com/gosuri/uitable/util/strutil"
|
8 | 9 |
"github.com/gosuri/uitable/util/wordwrap"
|
|
25 | 26 |
|
26 | 27 |
// Separator is the seperator for columns in the table. Default is "\t"
|
27 | 28 |
Separator string
|
|
29 |
|
|
30 |
mtx *sync.RWMutex
|
28 | 31 |
}
|
29 | 32 |
|
30 | 33 |
// New returns a new Table with default values
|
31 | 34 |
func New() *Table {
|
32 | 35 |
return &Table{
|
33 | 36 |
Separator: Separator,
|
|
37 |
mtx: new(sync.RWMutex),
|
34 | 38 |
}
|
35 | 39 |
}
|
36 | 40 |
|
37 | 41 |
// AddRow adds a new row to the table
|
38 | 42 |
func (t *Table) AddRow(data ...interface{}) *Table {
|
|
43 |
t.mtx.Lock()
|
|
44 |
defer t.mtx.Unlock()
|
39 | 45 |
r := NewRow(data...)
|
40 | 46 |
t.Rows = append(t.Rows, r)
|
41 | 47 |
return t
|
|
43 | 49 |
|
44 | 50 |
// String returns the string value of table
|
45 | 51 |
func (t *Table) String() string {
|
|
52 |
t.mtx.RLock()
|
|
53 |
defer t.mtx.RUnlock()
|
|
54 |
|
46 | 55 |
if len(t.Rows) == 0 {
|
47 | 56 |
return ""
|
48 | 57 |
}
|
0 | 0 |
package uitable
|
1 | 1 |
|
2 | 2 |
import (
|
|
3 |
"sync"
|
3 | 4 |
"testing"
|
4 | 5 |
)
|
5 | 6 |
|
|
42 | 43 |
t.Fatalf("need: %q | got: %q ", need, got)
|
43 | 44 |
}
|
44 | 45 |
}
|
|
46 |
|
|
47 |
func TestAddRow(t *testing.T) {
|
|
48 |
var wg sync.WaitGroup
|
|
49 |
table := New()
|
|
50 |
for i := 0; i < 100; i++ {
|
|
51 |
wg.Add(1)
|
|
52 |
go func() {
|
|
53 |
defer wg.Done()
|
|
54 |
table.AddRow("foo")
|
|
55 |
}()
|
|
56 |
}
|
|
57 |
wg.Wait()
|
|
58 |
if len(table.Rows) != 100 {
|
|
59 |
t.Fatal("want", 100, "got", len(table.Rows))
|
|
60 |
}
|
|
61 |
}
|