Created
May 27, 2020 04:16
-
-
Save rueian/a8ffe021df5f2399a3976059121b14cb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "container/ring" | |
| "fmt" | |
| "math/rand" | |
| "strconv" | |
| "sync/atomic" | |
| "unsafe" | |
| ) | |
| type Val struct { | |
| Ptr unsafe.Pointer | |
| } | |
| type Entry struct { | |
| URL string | |
| } | |
| func main() { | |
| buffer := ring.New(10) | |
| for i := 0; i < buffer.Len(); i++ { | |
| buffer.Value = &Val{} | |
| buffer = buffer.Next() | |
| } | |
| // producer | |
| go func() { | |
| for cur := buffer; ; cur = cur.Next() { | |
| if out := SwapOut(cur, &Entry{URL: strconv.Itoa(rand.Int())}); out != nil { | |
| fmt.Println("clean cuckoo") | |
| } | |
| } | |
| }() | |
| // consumer | |
| for cur := buffer; ; cur = cur.Next() { | |
| if out := SwapOut(cur, nil); out != nil { | |
| fmt.Println("scan:", out.URL) | |
| } | |
| } | |
| } | |
| func SwapOut(r *ring.Ring, n *Entry) *Entry { | |
| return (*Entry)(atomic.SwapPointer(&r.Value.(*Val).Ptr, unsafe.Pointer(n))) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment