From 3e7f31b1a2c6f541c62c2ed805c6d0195fe077e6 Mon Sep 17 00:00:00 2001 From: Dmitrii Okunev Date: Sat, 11 Jan 2025 14:10:39 +0000 Subject: [PATCH] Initial commit --- LICENSE | 121 ++++++++++++++ context.go | 30 ++++ do.go | 471 +++++++++++++++++++++++++++++++++++++++++++++++++++++ go.mod | 20 +++ go.sum | 37 +++++ gorex.go | 15 ++ map.go | 66 ++++++++ rwmutex.go | 212 ++++++++++++++++++++++++ 8 files changed, 972 insertions(+) create mode 100644 LICENSE create mode 100644 context.go create mode 100644 do.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 gorex.go create mode 100644 map.go create mode 100644 rwmutex.go diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/context.go b/context.go new file mode 100644 index 0000000..abf1e0a --- /dev/null +++ b/context.go @@ -0,0 +1,30 @@ +package xsync + +import ( + "context" +) + +type CtxKeyNoLogging struct{} + +func WithNoLogging(ctx context.Context, noLogging bool) context.Context { + return context.WithValue(ctx, CtxKeyNoLogging{}, noLogging) +} + +func IsNoLogging(ctx context.Context) bool { + v, _ := ctx.Value(CtxKeyNoLogging{}).(bool) + return v +} + +type CtxKeyEnableDeadlock struct{} + +func WithEnableDeadlock(ctx context.Context, enableDeadlock bool) context.Context { + return context.WithValue(ctx, CtxKeyEnableDeadlock{}, enableDeadlock) +} + +func IsEnableDeadlock(ctx context.Context) bool { + v, ok := ctx.Value(CtxKeyNoLogging{}).(bool) + if !ok { + return true + } + return v +} diff --git a/do.go b/do.go new file mode 100644 index 0000000..b92a8be --- /dev/null +++ b/do.go @@ -0,0 +1,471 @@ +package xsync + +import ( + "context" +) + +type Doer interface { + Do(context.Context, func()) +} + +func DoA1[A0 any]( + ctx context.Context, + m Doer, + fn func(A0), + a0 A0, +) { + m.Do(ctx, func() { + fn(a0) + }) +} + +func DoA2[A0, A1 any]( + ctx context.Context, + m Doer, + fn func(A0, A1), + a0 A0, + a1 A1, +) { + m.Do(ctx, func() { + fn(a0, a1) + }) +} + +func DoA1R1[A0, R0 any]( + ctx context.Context, + m Doer, + fn func(A0) R0, + a0 A0, +) R0 { + var ( + r0 R0 + ) + m.Do(ctx, func() { + r0 = fn(a0) + }) + return r0 +} + +func DoA2R1[A0, A1, R0 any]( + ctx context.Context, + m Doer, + fn func(A0, A1) R0, + a0 A0, + a1 A1, +) R0 { + var ( + r0 R0 + ) + m.Do(ctx, func() { + r0 = fn(a0, a1) + }) + return r0 +} + +func DoA3R1[A0, A1, A2, R0 any]( + ctx context.Context, + m Doer, + fn func(A0, A1, A2) R0, + a0 A0, + a1 A1, + a2 A2, +) R0 { + var ( + r0 R0 + ) + m.Do(ctx, func() { + r0 = fn(a0, a1, a2) + }) + return r0 +} + +func DoA3R2[A0, A1, A2, R0, R1 any]( + ctx context.Context, + m Doer, + fn func(A0, A1, A2) (R0, R1), + a0 A0, + a1 A1, + a2 A2, +) (R0, R1) { + var ( + r0 R0 + r1 R1 + ) + m.Do(ctx, func() { + r0, r1 = fn(a0, a1, a2) + }) + return r0, r1 +} + +func DoA4R1[A0, A1, A2, A3, R0 any]( + ctx context.Context, + m Doer, + fn func(A0, A1, A2, A3) R0, + a0 A0, + a1 A1, + a2 A2, + a3 A3, +) R0 { + var ( + r0 R0 + ) + m.Do(ctx, func() { + r0 = fn(a0, a1, a2, a3) + }) + return r0 +} + +func DoA1R2[A0, R0, R1 any]( + ctx context.Context, + m Doer, + fn func(A0) (R0, R1), + a0 A0, +) (R0, R1) { + var ( + r0 R0 + r1 R1 + ) + m.Do(ctx, func() { + r0, r1 = fn(a0) + }) + return r0, r1 +} + +func DoA2R2[A0, A1, R0, R1 any]( + ctx context.Context, + m Doer, + fn func(A0, A1) (R0, R1), + a0 A0, + a1 A1, +) (R0, R1) { + var ( + r0 R0 + r1 R1 + ) + m.Do(ctx, func() { + r0, r1 = fn(a0, a1) + }) + return r0, r1 +} + +func DoA2R3[A0, A1, R0, R1, R2 any]( + ctx context.Context, + m Doer, + fn func(A0, A1) (R0, R1, R2), + a0 A0, + a1 A1, +) (R0, R1, R2) { + var ( + r0 R0 + r1 R1 + r2 R2 + ) + m.Do(ctx, func() { + r0, r1, r2 = fn(a0, a1) + }) + return r0, r1, r2 +} + +func DoR1[R0 any]( + ctx context.Context, + m Doer, + fn func() R0, +) R0 { + var ( + r0 R0 + ) + m.Do(ctx, func() { + r0 = fn() + }) + return r0 +} + +func DoR2[R0, R1 any]( + ctx context.Context, + m Doer, + fn func() (R0, R1), +) (R0, R1) { + var ( + r0 R0 + r1 R1 + ) + m.Do(ctx, func() { + r0, r1 = fn() + }) + return r0, r1 +} + +func DoR3[R0, R1, R2 any]( + ctx context.Context, + m Doer, + fn func() (R0, R1, R2), +) (R0, R1, R2) { + var ( + r0 R0 + r1 R1 + r2 R2 + ) + m.Do(ctx, func() { + r0, r1, r2 = fn() + }) + return r0, r1, r2 +} + +func DoR4[R0, R1, R2, R3 any]( + ctx context.Context, + m Doer, + fn func() (R0, R1, R2, R3), +) (R0, R1, R2, R3) { + var ( + r0 R0 + r1 R1 + r2 R2 + r3 R3 + ) + m.Do(ctx, func() { + r0, r1, r2, r3 = fn() + }) + return r0, r1, r2, r3 +} + +func DoA1R4[A0, R0, R1, R2, R3 any]( + ctx context.Context, + m Doer, + fn func(A0) (R0, R1, R2, R3), + a0 A0, +) (R0, R1, R2, R3) { + var ( + r0 R0 + r1 R1 + r2 R2 + r3 R3 + ) + m.Do(ctx, func() { + r0, r1, r2, r3 = fn(a0) + }) + return r0, r1, r2, r3 +} + +type RDoer interface { + RDo(context.Context, func()) +} + +func RDoA1[A0 any]( + ctx context.Context, + m RDoer, + fn func(A0), + a0 A0, +) { + m.RDo(ctx, func() { + fn(a0) + }) +} + +func RDoA2[A0, A1 any]( + ctx context.Context, + m RDoer, + fn func(A0, A1), + a0 A0, + a1 A1, +) { + m.RDo(ctx, func() { + fn(a0, a1) + }) +} + +func RDoA1R1[A0, R0 any]( + ctx context.Context, + m RDoer, + fn func(A0) R0, + a0 A0, +) R0 { + var ( + r0 R0 + ) + m.RDo(ctx, func() { + r0 = fn(a0) + }) + return r0 +} + +func RDoA2R1[A0, A1, R0 any]( + ctx context.Context, + m RDoer, + fn func(A0, A1) R0, + a0 A0, + a1 A1, +) R0 { + var ( + r0 R0 + ) + m.RDo(ctx, func() { + r0 = fn(a0, a1) + }) + return r0 +} + +func RDoA3R1[A0, A1, A2, R0 any]( + ctx context.Context, + m RDoer, + fn func(A0, A1, A2) R0, + a0 A0, + a1 A1, + a2 A2, +) R0 { + var ( + r0 R0 + ) + m.RDo(ctx, func() { + r0 = fn(a0, a1, a2) + }) + return r0 +} + +func RDoA4R1[A0, A1, A2, A3, R0 any]( + ctx context.Context, + m RDoer, + fn func(A0, A1, A2, A3) R0, + a0 A0, + a1 A1, + a2 A2, + a3 A3, +) R0 { + var ( + r0 R0 + ) + m.RDo(ctx, func() { + r0 = fn(a0, a1, a2, a3) + }) + return r0 +} + +func RDoA1R2[A0, R0, R1 any]( + ctx context.Context, + m RDoer, + fn func(A0) (R0, R1), + a0 A0, +) (R0, R1) { + var ( + r0 R0 + r1 R1 + ) + m.RDo(ctx, func() { + r0, r1 = fn(a0) + }) + return r0, r1 +} + +func RDoA2R2[A0, A1, R0, R1 any]( + ctx context.Context, + m RDoer, + fn func(A0, A1) (R0, R1), + a0 A0, + a1 A1, +) (R0, R1) { + var ( + r0 R0 + r1 R1 + ) + m.RDo(ctx, func() { + r0, r1 = fn(a0, a1) + }) + return r0, r1 +} + +func RDoA2R3[A0, A1, R0, R1, R2 any]( + ctx context.Context, + m RDoer, + fn func(A0, A1) (R0, R1, R2), + a0 A0, + a1 A1, +) (R0, R1, R2) { + var ( + r0 R0 + r1 R1 + r2 R2 + ) + m.RDo(ctx, func() { + r0, r1, r2 = fn(a0, a1) + }) + return r0, r1, r2 +} + +func RDoR1[R0 any]( + ctx context.Context, + m RDoer, + fn func() R0, +) R0 { + var ( + r0 R0 + ) + m.RDo(ctx, func() { + r0 = fn() + }) + return r0 +} + +func RDoR2[R0, R1 any]( + ctx context.Context, + m RDoer, + fn func() (R0, R1), +) (R0, R1) { + var ( + r0 R0 + r1 R1 + ) + m.RDo(ctx, func() { + r0, r1 = fn() + }) + return r0, r1 +} + +func RDoR3[R0, R1, R2 any]( + ctx context.Context, + m RDoer, + fn func() (R0, R1, R2), +) (R0, R1, R2) { + var ( + r0 R0 + r1 R1 + r2 R2 + ) + m.RDo(ctx, func() { + r0, r1, r2 = fn() + }) + return r0, r1, r2 +} + +func RDoR4[R0, R1, R2, R3 any]( + ctx context.Context, + m RDoer, + fn func() (R0, R1, R2, R3), +) (R0, R1, R2, R3) { + var ( + r0 R0 + r1 R1 + r2 R2 + r3 R3 + ) + m.RDo(ctx, func() { + r0, r1, r2, r3 = fn() + }) + return r0, r1, r2, r3 +} + +func RDoA1R4[A0, R0, R1, R2, R3 any]( + ctx context.Context, + m RDoer, + fn func(A0) (R0, R1, R2, R3), + a0 A0, +) (R0, R1, R2, R3) { + var ( + r0 R0 + r1 R1 + r2 R2 + r3 R3 + ) + m.RDo(ctx, func() { + r0, r1, r2, r3 = fn(a0) + }) + return r0, r1, r2, r3 +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a0958dd --- /dev/null +++ b/go.mod @@ -0,0 +1,20 @@ +module github.com/xaionaro-go/xsync + +go 1.22.2 + +require ( + github.com/facebookincubator/go-belt v0.0.0-20240707112111-9cf347bf49e2 + github.com/xaionaro-go/gorex v0.0.0-20241010205749-bcd59d639c4d +) + +require ( + github.com/go-ng/slices v0.0.0-20230703171042-6195d35636a2 // indirect + github.com/go-ng/sort v0.0.0-20220617173827-2cc7cd04f7c7 // indirect + github.com/go-ng/xsort v0.0.0-20220617174223-1d146907bccc // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/huandu/go-tls v0.0.0-20200109070953-6f75fb441850 // indirect + github.com/phuslu/goid v1.0.1 // indirect + github.com/xaionaro-go/spinlock v0.0.0-20200518175509-30e6d1ce68a1 // indirect + golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df // indirect + golang.org/x/sys v0.9.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..de55bf8 --- /dev/null +++ b/go.sum @@ -0,0 +1,37 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/facebookincubator/go-belt v0.0.0-20240707112111-9cf347bf49e2 h1:TjgMDyXmX5ZGuDDS98ol5CLcVtrIGHNwQtA24Z2xBrY= +github.com/facebookincubator/go-belt v0.0.0-20240707112111-9cf347bf49e2/go.mod h1:BLkOQHXT14GLgKvM22LB/fDcq1stjijrTOJQEk3xrUA= +github.com/go-ng/slices v0.0.0-20230703171042-6195d35636a2 h1:UkoycH6lT7QfBw3LqHLe6GdFRhxScvVaI7A5oiAjy5s= +github.com/go-ng/slices v0.0.0-20230703171042-6195d35636a2/go.mod h1:bVEceuoz83G4yjq9Os7lCYe+lf46uY8EFEHkxSCywvM= +github.com/go-ng/sort v0.0.0-20220617173827-2cc7cd04f7c7 h1:Ng6QMSlQSB+goG6430/Fp7O4YO2BJZXZJaldtg+7kEc= +github.com/go-ng/sort v0.0.0-20220617173827-2cc7cd04f7c7/go.mod h1:QUXmOopthsqLYJ+rAybuCf16J7qQm60TLVdQR0w1Nus= +github.com/go-ng/xsort v0.0.0-20220617174223-1d146907bccc h1:VNz633GRJx2/hL0SpBNoNlLid4xtyi7LSJP1kHpD2Fo= +github.com/go-ng/xsort v0.0.0-20220617174223-1d146907bccc/go.mod h1:Pz/V4pxeXP0hjBlXIrm2ehR0GJ0l4Bon3fsOl6TmoJs= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/huandu/go-tls v0.0.0-20200109070953-6f75fb441850 h1:e6Xuec7psx1wWcYffIzWzhXBBFOJ526073fie9Cc79c= +github.com/huandu/go-tls v0.0.0-20200109070953-6f75fb441850/go.mod h1:WeItecBdaIdUBRb7cSMMk+rq41iFKhf6Q9mDRDpbdec= +github.com/phuslu/goid v1.0.1 h1:74sob8Rch+WJCROvccSbvxn0Pz5RBvIf57MvesjbPNo= +github.com/phuslu/goid v1.0.1/go.mod h1:txc2fUIdrdnn+v9Vq+QpiPQ3dnrXEchjoVDgic+r+L0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/xaionaro-go/gorex v0.0.0-20241010205749-bcd59d639c4d h1:9DyH0lboWWzKUwiqGmp9sTZ3bSPhgJHiiWgV+hqY9Uo= +github.com/xaionaro-go/gorex v0.0.0-20241010205749-bcd59d639c4d/go.mod h1:yI0EvHC6Ir5WIZp3tEk7o42/QqeTb9pkII+T8p4FlPo= +github.com/xaionaro-go/spinlock v0.0.0-20190309154744-55278e21e817/go.mod h1:Nb/15eS0BMty6TMuWgRQM8WCDIUlyPZagcpchHT6c9Y= +github.com/xaionaro-go/spinlock v0.0.0-20200518175509-30e6d1ce68a1 h1:1Kqw9dv2LnznIhJoMt3dNzc/ctSj6VHjyGh4YZHjpE4= +github.com/xaionaro-go/spinlock v0.0.0-20200518175509-30e6d1ce68a1/go.mod h1:UwmTXX+EpoEYHuy0rSys1Rp5PW+eVTgZSjgMVLJENKg= +golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df h1:UA2aFVmmsIlefxMk29Dp2juaUSth8Pyn3Tq5Y5mJGME= +golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= +golang.org/x/sys v0.0.0-20200107162124-548cf772de50/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s= +golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/gorex.go b/gorex.go new file mode 100644 index 0000000..14d81c9 --- /dev/null +++ b/gorex.go @@ -0,0 +1,15 @@ +package xsync + +import ( + "context" + + "github.com/xaionaro-go/gorex" +) + +type Gorex struct { + gorex.Mutex +} + +func (g *Gorex) Do(ctx context.Context, callback func()) { + g.Mutex.LockCtxDo(ctx, callback) +} diff --git a/map.go b/map.go new file mode 100644 index 0000000..90f3c75 --- /dev/null +++ b/map.go @@ -0,0 +1,66 @@ +package xsync + +import ( + "sync" +) + +type Map[K comparable, V any] struct { + sync.Map +} + +func (m *Map[K, V]) CompareAndDelete(key K, old V) (deleted bool) { + return m.Map.CompareAndDelete(key, old) +} + +func (m *Map[K, V]) CompareAndSwap(key K, old, new V) (swapped bool) { + return m.Map.CompareAndSwap(key, old, new) +} + +func (m *Map[K, V]) Delete(key K) { + m.Map.Delete(key) +} + +func (m *Map[K, V]) Load(key K) (V, bool) { + value, ok := m.Map.Load(key) + if !ok { + var zeroValue V + return zeroValue, false + } + return value.(V), true +} + +func (m *Map[K, V]) LoadAndDelete(key K) (V, bool) { + value, loaded := m.Map.LoadAndDelete(key) + if !loaded { + var zeroValue V + return zeroValue, false + } + return value.(V), true +} +func (m *Map[K, V]) LoadOrStore(key K, value V) (V, bool) { + actual, loaded := m.Map.LoadOrStore(key, value) + if !loaded { + var zeroValue V + return zeroValue, false + } + return actual.(V), true +} + +func (m *Map[K, V]) Range(f func(key K, value V) bool) { + m.Map.Range(func(key, value any) bool { + return f(key.(K), value.(V)) + }) +} + +func (m *Map[K, V]) Store(key K, value V) { + m.Map.Store(key, value) +} + +func (m *Map[K, V]) Swap(key K, value V) (V, bool) { + previous, loaded := m.Map.Swap(key, value) + if !loaded { + var zeroValue V + return zeroValue, false + } + return previous.(V), true +} diff --git a/rwmutex.go b/rwmutex.go new file mode 100644 index 0000000..df7f1a8 --- /dev/null +++ b/rwmutex.go @@ -0,0 +1,212 @@ +package xsync + +import ( + "context" + "fmt" + "runtime" + "sync" + "time" + + "github.com/facebookincubator/go-belt/tool/logger" +) + +type lockType uint + +const ( + lockTypeUndefined = lockType(iota) + lockTypeWrite + lockTypeRead +) + +func (lt lockType) String() string { + switch lt { + case lockTypeUndefined: + return "" + case lockTypeWrite: + return "Lock" + case lockTypeRead: + return "RLock" + default: + return fmt.Sprintf("", uint(lt)) + } +} + +func fixCtx(ctx context.Context) context.Context { + if ctx == nil { + ctx = context.Background() + } + return ctx +} + +type Mutex = RWMutex + +type RWMutex struct { + mutex sync.RWMutex + + OverrideTimeout time.Duration + PanicOnDeadlock *bool + cancelFunc context.CancelFunc + deadlockNotifier *time.Timer +} + +func (m *Mutex) ManualRLock(ctx context.Context) { + m.manualLock(ctx, lockTypeRead) +} + +func (m *Mutex) ManualLock(ctx context.Context) { + m.manualLock(ctx, lockTypeWrite) +} + +func (m *Mutex) manualLock(ctx context.Context, lockType lockType) { + ctx = fixCtx(ctx) + noLogging := IsNoLogging(ctx) + l := logger.FromCtx(ctx) + if !noLogging { + l.Tracef("%sing", lockType) + } + switch lockType { + case lockTypeWrite: + m.mutex.Lock() + m.startDeadlockDetector(ctx) + case lockTypeRead: + m.mutex.RLock() + } + + if !noLogging { + l.Tracef("%sed", lockType) + } +} + +func (m *Mutex) startDeadlockDetector(ctx context.Context) { + ctx, m.cancelFunc = context.WithCancel(ctx) + timeout := time.Minute + if m.OverrideTimeout != 0 { + timeout = m.OverrideTimeout + } + if timeout <= 0 { + return + } + + deadlockNotifier := time.NewTimer(time.Minute) + go func() { + select { + case <-ctx.Done(): + return + case <-deadlockNotifier.C: + } + allStacks := make([]byte, 1024*1024) + n := runtime.Stack(allStacks, true) + allStacks = allStacks[:n] + if IsEnableDeadlock(ctx) { + if m.PanicOnDeadlock == nil || *m.PanicOnDeadlock { + logger.Panicf(ctx, "got a deadlock in:\n%s", allStacks) + } else { + logger.Errorf(ctx, "got a deadlock in:\n%s", allStacks) + } + } + }() + m.deadlockNotifier = deadlockNotifier +} + +func (m *Mutex) ManualTryRLock(ctx context.Context) bool { + return m.manualTryLock(ctx, lockTypeRead) +} + +func (m *Mutex) ManualTryLock(ctx context.Context) bool { + return m.manualTryLock(ctx, lockTypeWrite) +} + +func (m *Mutex) manualTryLock(ctx context.Context, lockType lockType) bool { + ctx = fixCtx(ctx) + noLogging := IsNoLogging(ctx) + l := logger.FromCtx(ctx) + if !noLogging { + l.Tracef("Try%sing", lockType) + } + + var result bool + switch lockType { + case lockTypeWrite: + result = m.mutex.TryLock() + if result { + m.startDeadlockDetector(ctx) + } + case lockTypeRead: + result = m.mutex.TryRLock() + } + + if !noLogging { + l.Tracef("Try%sed, result: %v", lockType, result) + } + return result +} + +func (m *Mutex) ManualRUnlock(ctx context.Context) { + m.manualUnlock(ctx, lockTypeRead) +} + +func (m *Mutex) ManualUnlock(ctx context.Context) { + m.manualUnlock(ctx, lockTypeWrite) +} + +func (m *Mutex) manualUnlock(ctx context.Context, lockType lockType) { + ctx = fixCtx(ctx) + noLogging := IsNoLogging(ctx) + l := logger.FromCtx(ctx) + if !noLogging { + l.Tracef("un%sing", lockType) + } + + switch lockType { + case lockTypeWrite: + if m.deadlockNotifier != nil { + m.deadlockNotifier.Stop() + m.cancelFunc() + m.deadlockNotifier, m.cancelFunc = nil, nil + } + + m.mutex.Unlock() + case lockTypeRead: + m.mutex.RUnlock() + } + + if !noLogging { + l.Tracef("un%sed", lockType) + } +} + +func (m *Mutex) Do( + ctx context.Context, + fn func(), +) { + m.ManualLock(ctx) + defer m.ManualUnlock(ctx) + fn() +} + +func (m *Mutex) RDo( + ctx context.Context, + fn func(), +) { + m.ManualRLock(ctx) + defer m.ManualRUnlock(ctx) + fn() +} + +func (m *Mutex) UDo( + ctx context.Context, + fn func(), +) { + m.ManualUnlock(ctx) + defer m.ManualLock(ctx) + fn() +} + +func (m *Mutex) URDo( + ctx context.Context, + fn func(), +) { + m.ManualRUnlock(ctx) + defer m.ManualRLock(ctx) + fn() +}