12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package syncutils
- import (
- "fmt"
- "strconv"
- "testing"
- )
- func TestSyncVar(t *testing.T) {
- syncSlice := NewSyncVar([]string{"aaa", "bbb", "ccc"}, false)
- syncSlice.ForWrite(func(s []string) []string {
- return append(s, "ddd")
- })
- syncSlice.ForRead(func(s []string) {
- for i, v := range s {
- fmt.Println("Index", strconv.Itoa(i)+":", v)
- }
- fmt.Println()
- })
- syncSlice.ForWrite(func(s []string) []string {
- for i, v := range s {
- if v == "ddd" {
- return append(s[:i], s[i+1:]...)
- }
- }
- return s
- })
- syncSlice.ForRead(func(s []string) {
- for i, v := range s {
- fmt.Println("Index", strconv.Itoa(i)+":", v)
- }
- fmt.Println()
- })
- rwSyncSlice := NewSyncVar([]string{"aaa", "bbb", "ccc"}, true)
- rwSyncSlice.ForWrite(func(s []string) []string {
- return append(s, "ddd")
- })
- rwSyncSlice.ForRead(func(s []string) {
- for i, v := range s {
- fmt.Println("Index", strconv.Itoa(i)+":", v)
- }
- fmt.Println()
- })
- rwSyncSlice.ForWrite(func(s []string) []string {
- for i, v := range s {
- if v == "ddd" {
- return append(s[:i], s[i+1:]...)
- }
- }
- return s
- })
- rwSyncSlice.ForRead(func(s []string) {
- for i, v := range s {
- fmt.Println("Index", strconv.Itoa(i)+":", v)
- }
- fmt.Println()
- })
- type Student struct {
- Name string
- Age int
- }
- rwSyncStruct := NewSyncVar(&Student{
- Name: "test",
- Age: 10,
- }, true)
- rwSyncStruct.ForRead(func(v *Student) {
- fmt.Println("Name:", v.Name)
- fmt.Println("Age:", v.Age)
- fmt.Println()
- })
- rwSyncStruct.ForWrite(func(v *Student) *Student {
- v.Name = "test_new"
- v.Age = 20
- return v
- })
- rwSyncStruct.ForRead(func(v *Student) {
- fmt.Println("Name:", v.Name)
- fmt.Println("Age:", v.Age)
- fmt.Println()
- })
- }
|