sync_var_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package syncutils
  2. import (
  3. "fmt"
  4. "strconv"
  5. "testing"
  6. )
  7. func TestSyncVar(t *testing.T) {
  8. syncSlice := NewSyncVar([]string{"aaa", "bbb", "ccc"}, false)
  9. syncSlice.ForWrite(func(s []string) []string {
  10. return append(s, "ddd")
  11. })
  12. syncSlice.ForRead(func(s []string) {
  13. for i, v := range s {
  14. fmt.Println("Index", strconv.Itoa(i)+":", v)
  15. }
  16. fmt.Println()
  17. })
  18. syncSlice.ForWrite(func(s []string) []string {
  19. for i, v := range s {
  20. if v == "ddd" {
  21. return append(s[:i], s[i+1:]...)
  22. }
  23. }
  24. return s
  25. })
  26. syncSlice.ForRead(func(s []string) {
  27. for i, v := range s {
  28. fmt.Println("Index", strconv.Itoa(i)+":", v)
  29. }
  30. fmt.Println()
  31. })
  32. rwSyncSlice := NewSyncVar([]string{"aaa", "bbb", "ccc"}, true)
  33. rwSyncSlice.ForWrite(func(s []string) []string {
  34. return append(s, "ddd")
  35. })
  36. rwSyncSlice.ForRead(func(s []string) {
  37. for i, v := range s {
  38. fmt.Println("Index", strconv.Itoa(i)+":", v)
  39. }
  40. fmt.Println()
  41. })
  42. rwSyncSlice.ForWrite(func(s []string) []string {
  43. for i, v := range s {
  44. if v == "ddd" {
  45. return append(s[:i], s[i+1:]...)
  46. }
  47. }
  48. return s
  49. })
  50. rwSyncSlice.ForRead(func(s []string) {
  51. for i, v := range s {
  52. fmt.Println("Index", strconv.Itoa(i)+":", v)
  53. }
  54. fmt.Println()
  55. })
  56. type Student struct {
  57. Name string
  58. Age int
  59. }
  60. rwSyncStruct := NewSyncVar(&Student{
  61. Name: "test",
  62. Age: 10,
  63. }, true)
  64. rwSyncStruct.ForRead(func(v *Student) {
  65. fmt.Println("Name:", v.Name)
  66. fmt.Println("Age:", v.Age)
  67. fmt.Println()
  68. })
  69. rwSyncStruct.ForWrite(func(v *Student) *Student {
  70. v.Name = "test_new"
  71. v.Age = 20
  72. return v
  73. })
  74. rwSyncStruct.ForRead(func(v *Student) {
  75. fmt.Println("Name:", v.Name)
  76. fmt.Println("Age:", v.Age)
  77. fmt.Println()
  78. })
  79. }