├── .gitignore ├── LICENSE ├── README.md ├── tests ├── atomic_int_test.go ├── atomic_pointer_test.go ├── newless_pool_test.go ├── one_time_cond_test.go ├── spin_lock_test.go └── sync_queue_test.go └── xnsyncutil ├── atomic_int.go ├── atomic_pointer.go ├── newless_pool.go ├── one_time_cond.go ├── spin_lock.go └── sync_queue.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | vendor/ 16 | .idea/ 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-xnsyncutil 2 | My Go sync utils 3 | 4 | Install: 5 | 6 | `govendor get github.com/xiaonanln/go-xnsyncutil/xnsyncutil` 7 | 8 | Document: https://godoc.org/github.com/xiaonanln/go-xnsyncutil/xnsyncutil 9 | 10 | -------------------------------------------------------------------------------- /tests/atomic_int_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "testing" 5 | 6 | "sync" 7 | 8 | "time" 9 | 10 | "github.com/xiaonanln/go-xnsyncutil/xnsyncutil" 11 | ) 12 | 13 | func TestAtomicInt(t *testing.T) { 14 | var ai xnsyncutil.AtomicInt 15 | if ai.Load() != 0 { 16 | t.Errorf("should be initialized to 0") 17 | } 18 | ai.Store(100) 19 | if ai.Load() != 100 { 20 | t.Errorf("load wrong value") 21 | } 22 | ai.Add(100) 23 | if ai.Load() != 200 { 24 | t.Errorf("load wrong value") 25 | } 26 | 27 | var wait sync.WaitGroup 28 | concurrent := 2 29 | wait.Add(concurrent) 30 | 31 | for i := 0; i < concurrent; i++ { 32 | var delta int 33 | if i%2 == 0 { 34 | delta = -1 35 | } else { 36 | delta = 1 37 | } 38 | go func() { 39 | for i := 0; i < 1000; i++ { 40 | ai.Add(delta) 41 | time.Sleep(time.Microsecond) 42 | } 43 | wait.Done() 44 | }() 45 | } 46 | 47 | wait.Wait() 48 | if ai.Load() != 200 { 49 | t.Errorf("load wrong value after fuzzy concurrent add") 50 | } 51 | } 52 | 53 | func TestAtomicInt64(t *testing.T) { 54 | var ai xnsyncutil.AtomicInt64 55 | if ai.Load() != 0 { 56 | t.Errorf("should be initialized to 0") 57 | } 58 | ai.Store(100) 59 | if ai.Load() != 100 { 60 | t.Errorf("load wrong value") 61 | } 62 | ai.Add(100) 63 | if ai.Load() != 200 { 64 | t.Errorf("load wrong value") 65 | } 66 | 67 | var wait sync.WaitGroup 68 | concurrent := 2 69 | wait.Add(concurrent) 70 | 71 | for i := 0; i < concurrent; i++ { 72 | var delta int64 73 | if i%2 == 0 { 74 | delta = -1 75 | } else { 76 | delta = 1 77 | } 78 | go func() { 79 | for i := 0; i < 1000; i++ { 80 | ai.Add(delta) 81 | time.Sleep(time.Microsecond) 82 | } 83 | wait.Done() 84 | }() 85 | } 86 | 87 | wait.Wait() 88 | if ai.Load() != 200 { 89 | t.Errorf("load wrong value after fuzzy concurrent add") 90 | } 91 | } 92 | 93 | func TestAtomicInt32(t *testing.T) { 94 | var ai xnsyncutil.AtomicInt32 95 | if ai.Load() != 0 { 96 | t.Errorf("should be initialized to 0") 97 | } 98 | ai.Store(100) 99 | if ai.Load() != 100 { 100 | t.Errorf("load wrong value") 101 | } 102 | ai.Add(100) 103 | if ai.Load() != 200 { 104 | t.Errorf("load wrong value") 105 | } 106 | 107 | var wait sync.WaitGroup 108 | concurrent := 2 109 | wait.Add(concurrent) 110 | 111 | for i := 0; i < concurrent; i++ { 112 | var delta int32 113 | if i%2 == 0 { 114 | delta = -1 115 | } else { 116 | delta = 1 117 | } 118 | go func() { 119 | for i := 0; i < 1000; i++ { 120 | ai.Add(delta) 121 | time.Sleep(time.Microsecond) 122 | } 123 | wait.Done() 124 | }() 125 | } 126 | 127 | wait.Wait() 128 | if ai.Load() != 200 { 129 | t.Errorf("load wrong value after fuzzy concurrent add") 130 | } 131 | } 132 | 133 | func TestAtomicBool(t *testing.T) { 134 | var ab xnsyncutil.AtomicBool 135 | if ab.Load() { 136 | t.Errorf("should be initialized to false") 137 | } 138 | ab.Store(true) 139 | if ab.Load() != true { 140 | t.Errorf("load wrong value") 141 | } 142 | ab.Store(false) 143 | if ab.Load() != false { 144 | t.Errorf("load wrong value") 145 | } 146 | 147 | var wait sync.WaitGroup 148 | concurrent := 2 149 | wait.Add(concurrent) 150 | 151 | for i := 0; i < concurrent; i++ { 152 | val := i%2 == 0 153 | go func() { 154 | for i := 0; i < 1000; i++ { 155 | ab.Store(val) 156 | time.Sleep(time.Microsecond) 157 | } 158 | wait.Done() 159 | }() 160 | } 161 | 162 | wait.Wait() 163 | } 164 | -------------------------------------------------------------------------------- /tests/atomic_pointer_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "testing" 5 | 6 | "unsafe" 7 | 8 | "github.com/xiaonanln/go-xnsyncutil/xnsyncutil" 9 | ) 10 | 11 | func TestAtomicPointer(t *testing.T) { 12 | var ai xnsyncutil.AtomicPointer 13 | var a int 14 | ai.Store((unsafe.Pointer(&a))) 15 | *(*int)(ai.Load()) = 1 16 | if a != 1 { 17 | t.Errorf("a should be 1, but is %d", a) 18 | } 19 | b := 100 20 | 21 | ai.Store((unsafe.Pointer(&b))) 22 | *(*int)(ai.Load()) = 200 23 | if b != 200 { 24 | t.Errorf("b should be 200, but is %d", b) 25 | } 26 | 27 | if unsafe.Pointer(&b) != ai.Load() { 28 | t.Errorf("&b is %p, but load %p", &b, ai.Load()) 29 | } 30 | //ai.Store(&b) 31 | } 32 | -------------------------------------------------------------------------------- /tests/newless_pool_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/xiaonanln/go-xnsyncutil/xnsyncutil" 7 | ) 8 | 9 | func TestNewNewlessPool(t *testing.T) { 10 | pool := xnsyncutil.NewNewlessPool() 11 | if pool == nil { 12 | t.Errorf("pool is nil") 13 | } 14 | } 15 | 16 | func TestNewlessPool_Basic(t *testing.T) { 17 | pool := xnsyncutil.NewNewlessPool() 18 | pool.Put(1) 19 | if pool.Get().(int) != 1 { 20 | t.Errorf("put 1 but get not 1") 21 | } 22 | 23 | if pool.TryGet() != nil { 24 | t.Errorf("should be nil") 25 | } 26 | 27 | pool.Put(3) 28 | if pool.TryGet().(int) != 3 { 29 | t.Error("wrong") 30 | } 31 | 32 | go func() { 33 | if pool.Get().(int) != 2 { 34 | t.Errorf("wrong") 35 | } 36 | }() 37 | pool.Put(2) 38 | } 39 | -------------------------------------------------------------------------------- /tests/one_time_cond_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "testing" 5 | 6 | "time" 7 | 8 | "github.com/xiaonanln/go-xnsyncutil/xnsyncutil" 9 | ) 10 | 11 | func TestOneTimeCond(t *testing.T) { 12 | cond := xnsyncutil.NewOneTimeCond() 13 | if cond.IsSignalled() { 14 | t.Errorf("should not be signalled when created") 15 | } 16 | 17 | startWaitTime := time.Now() 18 | 19 | go func() { 20 | time.Sleep(time.Millisecond * 100) 21 | cond.Signal() 22 | }() 23 | 24 | cond.Wait() 25 | if time.Now().Sub(startWaitTime) < time.Millisecond*90 { 26 | t.Errorf("wait return too soon") 27 | } 28 | 29 | cond.Wait() // should return immediately 30 | } 31 | -------------------------------------------------------------------------------- /tests/spin_lock_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/xiaonanln/go-xnsyncutil/xnsyncutil" 7 | 8 | "fmt" 9 | 10 | "sync" 11 | ) 12 | 13 | func TestSpinLock(t *testing.T) { 14 | 15 | var lock xnsyncutil.SpinLock 16 | var val int 17 | const N = 10000 18 | var wait sync.WaitGroup 19 | wait.Add(2) 20 | 21 | go func() { 22 | for i := 0; i < N; i++ { 23 | lock.Lock() 24 | val += 1 25 | lock.Unlock() 26 | } 27 | wait.Done() 28 | }() 29 | 30 | go func() { 31 | for i := 0; i < N; i++ { 32 | lock.Lock() 33 | val += 1 34 | lock.Unlock() 35 | } 36 | wait.Done() 37 | }() 38 | 39 | wait.Wait() 40 | if val != N*2 { 41 | t.Fatalf("val should be %d, but is %d", N*2, val) 42 | } 43 | fmt.Printf("%d\n", val) 44 | } 45 | 46 | func BenchmarkSpinLock(b *testing.B) { 47 | 48 | var lock xnsyncutil.SpinLock 49 | const N = 10000 50 | 51 | for i := 0; i < b.N; i++ { 52 | var val int 53 | var wait sync.WaitGroup 54 | wait.Add(2) 55 | 56 | go func() { 57 | for i := 0; i < N; i++ { 58 | lock.Lock() 59 | val += 1 60 | lock.Unlock() 61 | } 62 | wait.Done() 63 | }() 64 | 65 | go func() { 66 | for i := 0; i < N; i++ { 67 | lock.Lock() 68 | val += 1 69 | lock.Unlock() 70 | } 71 | wait.Done() 72 | }() 73 | 74 | wait.Wait() 75 | } 76 | } 77 | func BenchmarkMutex(b *testing.B) { 78 | 79 | var lock sync.Mutex 80 | const N = 10000 81 | 82 | for i := 0; i < b.N; i++ { 83 | var val int 84 | var wait sync.WaitGroup 85 | wait.Add(2) 86 | 87 | go func() { 88 | for i := 0; i < N; i++ { 89 | lock.Lock() 90 | val += 1 91 | lock.Unlock() 92 | } 93 | wait.Done() 94 | }() 95 | 96 | go func() { 97 | for i := 0; i < N; i++ { 98 | lock.Lock() 99 | val += 1 100 | lock.Unlock() 101 | } 102 | wait.Done() 103 | }() 104 | 105 | wait.Wait() 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /tests/sync_queue_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "math/rand" 5 | "testing" 6 | 7 | . "github.com/xiaonanln/go-xnsyncutil/xnsyncutil" 8 | ) 9 | 10 | const ( 11 | SEQ_TEST_N = 100000 12 | FUZZY_TEST_N = 100000 13 | ) 14 | 15 | func TestSyncQueue_Seq(t *testing.T) { 16 | q := NewSyncQueue() 17 | seqTestSyncQueue(t, q) 18 | } 19 | 20 | func TestSyncQueue_Fuzzy(t *testing.T) { 21 | q := NewSyncQueue() 22 | fuzzyTestSyncQueue(t, q) 23 | } 24 | 25 | func seqTestSyncQueue(t *testing.T, q *SyncQueue) { 26 | vals := []interface{}{} 27 | for i := 0; i < SEQ_TEST_N; i++ { 28 | vals = append(vals, rand.Int()) 29 | } 30 | 31 | for i, val := range vals { 32 | q.Push(val) 33 | if q.Len() != -1 && q.Len() != i+1 { 34 | t.Fatalf("queue length should be %v, but is %v", i+1, q.Len()) 35 | } 36 | } 37 | 38 | for i := 0; i < SEQ_TEST_N; i++ { 39 | val := q.Pop() 40 | if val != vals[i] { 41 | t.Fatalf("pop val should be %v, but is %v", vals[i], val) 42 | } 43 | if q.Len() != -1 && q.Len() != SEQ_TEST_N-i-1 { 44 | t.Fatalf("queue length should be %v, but is %v", SEQ_TEST_N-i-1, q.Len()) 45 | } 46 | } 47 | 48 | if q.Len() != 0 { 49 | t.Fatal("not zero") 50 | } 51 | 52 | q.Close() 53 | if v := q.Pop(); v != nil { 54 | t.Fatal("not nil") 55 | } 56 | 57 | if v, ok := q.TryPop(); v != nil || !ok { 58 | t.Fatal("TryPop error after close") 59 | } 60 | } 61 | 62 | func fuzzyTestSyncQueue(t *testing.T, q *SyncQueue) { 63 | vals := []interface{}{} 64 | 65 | for i := 0; i < FUZZY_TEST_N; i++ { 66 | if q.Len() > 0 && rand.Float64() < 0.4 { 67 | v := q.Pop() 68 | if v != vals[0] { 69 | t.Fatalf("pop val should be %v, but is %v", vals[i], v) 70 | } 71 | vals = vals[1:] 72 | } else { 73 | v := rand.Int() 74 | vals = append(vals, v) 75 | q.Push(v) 76 | } 77 | 78 | if q.Len() != -1 && q.Len() != len(vals) { 79 | t.Fatalf("queue length should be %v, but is %v", len(vals), q.Len()) 80 | } 81 | } 82 | 83 | for _, val := range vals { 84 | pv := q.Pop() 85 | if val != pv { 86 | t.Fatalf("pop val should be %v, but is %v", val, pv) 87 | } 88 | } 89 | } 90 | 91 | type syncQueueByChannel struct { 92 | channel chan interface{} 93 | } 94 | 95 | func newSyncQueueByChan() *syncQueueByChannel { 96 | ch := &syncQueueByChannel{ 97 | channel: make(chan interface{}, 1000000), 98 | } 99 | return ch 100 | } 101 | 102 | func (q *syncQueueByChannel) Pop() interface{} { 103 | return <-q.channel 104 | } 105 | 106 | func (q *syncQueueByChannel) TryPop() (interface{}, bool) { 107 | select { 108 | case v := <-q.channel: 109 | return v, true 110 | default: 111 | return nil, false 112 | } 113 | } 114 | 115 | func (q *syncQueueByChannel) Push(v interface{}) { 116 | q.channel <- v 117 | } 118 | 119 | func (q *syncQueueByChannel) Len() int { 120 | return -1 121 | } 122 | 123 | func (q *syncQueueByChannel) Close() { 124 | close(q.channel) 125 | } 126 | 127 | func BenchmarkSyncQueue(b *testing.B) { 128 | q := NewSyncQueue() 129 | b.ResetTimer() 130 | 131 | for i := 0; i < b.N; i++ { 132 | q.Push(1) 133 | q.Pop() 134 | } 135 | } 136 | 137 | func BenchmarkSyncQueueByChannel(b *testing.B) { 138 | q := newSyncQueueByChan() 139 | for i := 0; i < b.N; i++ { 140 | q.Push(1) 141 | q.Pop() 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /xnsyncutil/atomic_int.go: -------------------------------------------------------------------------------- 1 | package xnsyncutil 2 | 3 | import "sync/atomic" 4 | 5 | type AtomicInt int64 6 | 7 | // Store int value atomically 8 | func (ai *AtomicInt) Store(v int) { 9 | atomic.StoreInt64((*int64)(ai), int64(v)) 10 | } 11 | 12 | // Add int value atomically 13 | func (ai *AtomicInt) Add(delta int) { 14 | atomic.AddInt64((*int64)(ai), int64(delta)) 15 | } 16 | 17 | // Load int value atomically 18 | func (ai *AtomicInt) Load() int { 19 | return int(atomic.LoadInt64((*int64)(ai))) 20 | } 21 | 22 | type AtomicInt64 int64 23 | 24 | // Store int value atomically 25 | func (ai *AtomicInt64) Store(v int64) { 26 | atomic.StoreInt64((*int64)(ai), v) 27 | } 28 | 29 | // Add int value atomically 30 | func (ai *AtomicInt64) Add(delta int64) { 31 | atomic.AddInt64((*int64)(ai), delta) 32 | } 33 | 34 | // Load int value atomically 35 | func (ai *AtomicInt64) Load() int64 { 36 | return atomic.LoadInt64((*int64)(ai)) 37 | } 38 | 39 | type AtomicInt32 int32 40 | 41 | // Store int value atomically 42 | func (ai *AtomicInt32) Store(v int32) { 43 | atomic.StoreInt32((*int32)(ai), v) 44 | } 45 | 46 | // Add int value atomically 47 | func (ai *AtomicInt32) Add(delta int32) { 48 | atomic.AddInt32((*int32)(ai), delta) 49 | } 50 | 51 | // Load int value atomically 52 | func (ai *AtomicInt32) Load() int32 { 53 | return atomic.LoadInt32((*int32)(ai)) 54 | } 55 | 56 | 57 | type AtomicBool AtomicInt 58 | 59 | // Store bool value atomically 60 | func (ab *AtomicBool) Store(v bool) { 61 | if v { 62 | (*AtomicInt)(ab).Store(1) 63 | } else { 64 | (*AtomicInt)(ab).Store(0) 65 | } 66 | } 67 | 68 | // Load bool value atomically 69 | func (ab *AtomicBool) Load() bool { 70 | return (*AtomicInt)(ab).Load() != 0 71 | } 72 | -------------------------------------------------------------------------------- /xnsyncutil/atomic_pointer.go: -------------------------------------------------------------------------------- 1 | package xnsyncutil 2 | 3 | import ( 4 | "unsafe" 5 | "sync/atomic" 6 | ) 7 | 8 | type AtomicPointer struct { 9 | ptr unsafe.Pointer 10 | } 11 | 12 | // Store ptr value atomically 13 | func (ap *AtomicPointer) Store(pointer unsafe.Pointer) { 14 | atomic.StorePointer(&ap.ptr, pointer) 15 | } 16 | 17 | 18 | // Load ptr value atomically 19 | func (ap *AtomicPointer) Load() unsafe.Pointer { 20 | return atomic.LoadPointer(&ap.ptr) 21 | } 22 | 23 | -------------------------------------------------------------------------------- /xnsyncutil/newless_pool.go: -------------------------------------------------------------------------------- 1 | package xnsyncutil 2 | 3 | import "sync" 4 | 5 | type NewlessPool struct { 6 | lock sync.Mutex 7 | availCond *sync.Cond 8 | items []interface{} 9 | } 10 | 11 | func NewNewlessPool() *NewlessPool { 12 | pool := &NewlessPool{ 13 | items: nil, 14 | } 15 | pool.availCond = sync.NewCond(&pool.lock) 16 | return pool 17 | } 18 | 19 | func (pool *NewlessPool) Get() (v interface{}) { 20 | pool.lock.Lock() 21 | for len(pool.items) == 0 { 22 | pool.availCond.Wait() 23 | } 24 | // pop the last item 25 | n := len(pool.items) 26 | v, pool.items[n-1] = pool.items[n-1], nil 27 | pool.items = pool.items[:n-1] 28 | pool.lock.Unlock() 29 | return 30 | } 31 | 32 | func (pool *NewlessPool) TryGet() (v interface{}) { 33 | pool.lock.Lock() 34 | n := len(pool.items) 35 | if n > 0 { 36 | // pop the last item 37 | v, pool.items[n-1] = pool.items[n-1], nil 38 | pool.items = pool.items[:n-1] 39 | } 40 | 41 | pool.lock.Unlock() 42 | return 43 | } 44 | 45 | func (pool *NewlessPool) Put(v interface{}) { 46 | pool.lock.Lock() 47 | pool.items = append(pool.items, v) 48 | pool.availCond.Signal() 49 | pool.lock.Unlock() 50 | } 51 | -------------------------------------------------------------------------------- /xnsyncutil/one_time_cond.go: -------------------------------------------------------------------------------- 1 | package xnsyncutil 2 | 3 | import "sync" 4 | 5 | // Synchronous condition which can be signalled only once 6 | type OneTimeCond struct { 7 | signalled bool 8 | lock sync.Mutex 9 | subcond *sync.Cond 10 | } 11 | 12 | // Create a new OneTimeCond 13 | func NewOneTimeCond() *OneTimeCond { 14 | cond := &OneTimeCond{} 15 | cond.subcond = sync.NewCond(&cond.lock) 16 | return cond 17 | } 18 | 19 | // Wait for condition to be signalled. 20 | // 21 | // If the condition was signalled before Wait, Wait returns immediately without blocking. 22 | func (cond *OneTimeCond) Wait() { 23 | cond.lock.Lock() 24 | if cond.signalled { 25 | cond.lock.Unlock() 26 | return 27 | } 28 | 29 | cond.subcond.Wait() 30 | cond.lock.Unlock() 31 | } 32 | 33 | // Signal the condition 34 | // 35 | // All goroutines waiting for the condition will be notified to continue 36 | func (cond *OneTimeCond) Signal() { 37 | cond.lock.Lock() 38 | cond.signalled = true 39 | cond.subcond.Broadcast() 40 | cond.lock.Unlock() 41 | } 42 | 43 | // Return if the condition is already signalled 44 | func (cond *OneTimeCond) IsSignalled() (signalled bool) { 45 | cond.lock.Lock() 46 | signalled = cond.signalled 47 | cond.lock.Unlock() 48 | return 49 | } 50 | -------------------------------------------------------------------------------- /xnsyncutil/spin_lock.go: -------------------------------------------------------------------------------- 1 | package xnsyncutil 2 | 3 | import ( 4 | "runtime" 5 | "sync/atomic" 6 | ) 7 | 8 | type SpinLock struct { 9 | locked int32 10 | } 11 | 12 | func (sl *SpinLock) Lock() { 13 | for !atomic.CompareAndSwapInt32(&sl.locked, 0, 1) { 14 | runtime.Gosched() 15 | } 16 | } 17 | 18 | func (sl *SpinLock) Unlock() { 19 | atomic.StoreInt32(&sl.locked, 0) 20 | } 21 | -------------------------------------------------------------------------------- /xnsyncutil/sync_queue.go: -------------------------------------------------------------------------------- 1 | package xnsyncutil 2 | 3 | import ( 4 | "sync" 5 | 6 | "gopkg.in/eapache/queue.v1" 7 | ) 8 | 9 | // Synchronous FIFO queue 10 | type SyncQueue struct { 11 | lock sync.Mutex 12 | popable *sync.Cond 13 | buffer *queue.Queue 14 | closed bool 15 | } 16 | 17 | // Create a new SyncQueue 18 | func NewSyncQueue() *SyncQueue { 19 | ch := &SyncQueue{ 20 | buffer: queue.New(), 21 | } 22 | ch.popable = sync.NewCond(&ch.lock) 23 | return ch 24 | } 25 | 26 | // Pop an item from SyncQueue, will block if SyncQueue is empty 27 | func (q *SyncQueue) Pop() (v interface{}) { 28 | c := q.popable 29 | buffer := q.buffer 30 | 31 | q.lock.Lock() 32 | for buffer.Length() == 0 && !q.closed { 33 | c.Wait() 34 | } 35 | 36 | if buffer.Length() > 0 { 37 | v = buffer.Peek() 38 | buffer.Remove() 39 | } 40 | 41 | q.lock.Unlock() 42 | return 43 | } 44 | 45 | // Try to pop an item from SyncQueue, will return immediately with bool=false if SyncQueue is empty 46 | func (q *SyncQueue) TryPop() (v interface{}, ok bool) { 47 | buffer := q.buffer 48 | 49 | q.lock.Lock() 50 | 51 | if buffer.Length() > 0 { 52 | v = buffer.Peek() 53 | buffer.Remove() 54 | ok = true 55 | } else if q.closed { 56 | ok = true 57 | } 58 | 59 | q.lock.Unlock() 60 | return 61 | } 62 | 63 | // Push an item to SyncQueue. Always returns immediately without blocking 64 | func (q *SyncQueue) Push(v interface{}) { 65 | q.lock.Lock() 66 | if !q.closed { 67 | q.buffer.Add(v) 68 | q.popable.Signal() 69 | } 70 | q.lock.Unlock() 71 | } 72 | 73 | // Get the length of SyncQueue 74 | func (q *SyncQueue) Len() (l int) { 75 | q.lock.Lock() 76 | l = q.buffer.Length() 77 | q.lock.Unlock() 78 | return 79 | } 80 | 81 | // Close SyncQueue 82 | // 83 | // After close, Pop will return nil without block, and TryPop will return v=nil, ok=True 84 | func (q *SyncQueue) Close() { 85 | q.lock.Lock() 86 | if !q.closed { 87 | q.closed = true 88 | q.popable.Signal() 89 | } 90 | q.lock.Unlock() 91 | } 92 | --------------------------------------------------------------------------------