Skip to content

Instantly share code, notes, and snippets.

@mkatychev
Created March 2, 2021 23:03
Show Gist options
  • Save mkatychev/6ed2c7f596004c6af117744d5e5b91f2 to your computer and use it in GitHub Desktop.
Save mkatychev/6ed2c7f596004c6af117744d5e5b91f2 to your computer and use it in GitHub Desktop.
Synchronous output
package main
import (
"errors"
"sync"
)
type QueueEntry struct {
id string
complete bool
}
type PolicyUsher struct {
mu sync.Mutex
activeJob string
queue []QueueEntry
}
func (u *PolicyUsher) GetEntry(jobID string) (*QueueEntry, bool) {
for _, v := range u.queue {
if jobID == v.id {
return &v, true
}
}
return nil, false
}
// Lock locks m.
// If the lock is already in use, the calling goroutine
// blocks until the mutex is available.
func (u *PolicyUsher) Start(jobID string) {
if len(u.queue) == 0 || u.activeJob == "" {
u.activeJob = jobID
u.mu.Lock()
}
u.queue = append(u.queue, QueueEntry{id: jobID, complete: false})
}
// Unlock unlocks m.
// It is a run-time error if m is not locked on entry to Unlock.
//
// A locked Mutex is not associated with a particular goroutine.
// It is allowed for one goroutine to lock a Mutex and then
// arrange for another goroutine to unlock it.
func (u *PolicyUsher) Complete(jobID string) error {
if u.activeJob == jobID {
u.mu.Unlock()
u.activeJob = ""
return nil
}
entry, ok := u.GetEntry(jobID)
if !ok {
return errors.New("jobID error")
}
entry.complete = true
return nil
}
func (u *PolicyUsher) Commit(jobID string) error {
if len(u.queue) == 0 {
return nil
}
if u.queue[0].id == jobID {
u.queue = u.queue[:len(u.queue)-1] // drain from left
return nil
}
// implement whaterver retry logic here
return errors.New("cannot commit jobID as it is not most recent")
}
func main() {
// test if the pop approach works
list := []int{1, 2, 3}
list = list[:len(list)-1]
println(list)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment