github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/cmd/test/others/func/thread/test.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "sync" 6 "time" 7 ) 8 9 var ( 10 total = 251 11 12 size = 100 13 c = SafeCounter{v: make(map[string]int)} 14 ) 15 16 func main() { 17 // runtime.GOMAXPROCS(1) 18 19 fmt.Println("=== start ===") 20 21 threadCount := getTheadCount(total, size) 22 23 var waitGroup sync.WaitGroup 24 waitGroup.Add(threadCount) 25 26 for i := 0; i < threadCount; i++ { 27 index := i 28 c.Inc("count") 29 30 fmt.Printf("index = %d\n", index) 31 32 recordNumb := getTheadRecordNum(total, size, threadCount, index) 33 34 go func() { 35 defer func() { 36 c.Dec("count") 37 waitGroup.Done() 38 }() 39 40 for recordIndex := 0; recordIndex < recordNumb; recordIndex++ { 41 fmt.Printf("gen %d - %d\n", index, recordIndex+1) 42 time.Sleep(time.Millisecond * 100) 43 } 44 }() 45 } 46 47 go func() { 48 for { 49 fmt.Printf("=thread count= %d\n", c.Value("count")) 50 time.Sleep(time.Millisecond * 50) 51 } 52 }() 53 54 waitGroup.Wait() 55 fmt.Println("=== end ===") 56 } 57 58 func getTheadCount(total, size int) (threadCount int) { 59 threadCount = total / size 60 if total%size > 0 { 61 threadCount++ 62 } 63 64 return 65 } 66 func getTheadRecordNum(total, size, theadCount, index int) (num int) { 67 if index == theadCount-1 { 68 num = total % size 69 } else { 70 num = size 71 } 72 73 return 74 } 75 76 type SafeCounter struct { 77 mu sync.Mutex 78 v map[string]int 79 } 80 81 func (c *SafeCounter) Inc(key string) { 82 c.mu.Lock() 83 c.v[key]++ 84 c.mu.Unlock() 85 } 86 func (c *SafeCounter) Dec(key string) { 87 c.mu.Lock() 88 c.v[key]-- 89 c.mu.Unlock() 90 } 91 func (c *SafeCounter) Value(key string) int { 92 c.mu.Lock() 93 defer c.mu.Unlock() 94 return c.v[key] 95 }