-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
48 additions
and
2 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,49 @@ | ||
# qfifo (On Progress) | ||
# qfifo | ||
|
||
A simple Go FIFO queue | ||
A simple Go FIFO queue. | ||
|
||
## How to Use | ||
|
||
## Queue | ||
`Queue` is a FIFO queue implementation, to create it simply call `New()`. | ||
``` | ||
q := qfifo.New(nil) | ||
q.Push(1) | ||
q.Push(2) | ||
.... | ||
``` | ||
|
||
Under the hood, `Queue` uses slice with default capacity of 10, to increase the capacity use `QueueOptions`. | ||
``` | ||
q = New(&QueueOptions{ | ||
InitialSize: 20, | ||
}) | ||
q.Push(1) | ||
q.Push(2) | ||
.... | ||
``` | ||
|
||
To add an element, use `Push()` and to pull an element out use `Pop()`. All method has internal lock so they are safe to be used in multiple go routine. | ||
|
||
## Publisher | ||
`Publisher` uses `Queue` and periodically pull element to be passed into a publish function. Common scenario to use `Publisher` such as logging, we want to buffer the logs and periodically write buffered logs to persistence media such as text file or database. In this case, we can do that inside the publish function and let logging methods to push logs to queue while publish function writes the logs into text file. | ||
|
||
To create a publisher: | ||
``` | ||
p, err = NewPublisher(PublisherArgs{ | ||
PublishFunc: func(p *Publisher, v interface{}) { | ||
// v is the pulled element | ||
fmt.Println(v.(int)) // assuming the queued elements are integers | ||
}, | ||
}) | ||
if err != nil { | ||
return err | ||
} | ||
defer p.Close() // make sure to call this | ||
p.Push(1) | ||
p.Push(2) | ||
.......... | ||
``` | ||
|
||
`PublishFunc` is non-blocking because will be called by internal go routine. If it is unset then `NewPublisher()` returns `ErrPublishFunctionUnset`. |