2024-10-26 23:09:32 +09:00
|
|
|
package fmsg
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
wstate atomic.Bool
|
2024-11-04 12:56:19 +09:00
|
|
|
dropped atomic.Uint64
|
2024-10-26 23:09:32 +09:00
|
|
|
withhold = make(chan struct{}, 1)
|
|
|
|
msgbuf = make(chan dOp, 64) // these ops are tiny so a large buffer is allocated for withholding output
|
|
|
|
|
|
|
|
dequeueOnce sync.Once
|
|
|
|
queueSync sync.WaitGroup
|
|
|
|
)
|
|
|
|
|
|
|
|
func dequeue() {
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case op := <-msgbuf:
|
|
|
|
op.Do()
|
|
|
|
queueSync.Done()
|
|
|
|
case <-withhold:
|
|
|
|
<-withhold
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
2024-11-04 12:56:19 +09:00
|
|
|
// queue submits ops to msgbuf but drops messages
|
|
|
|
// when the buffer is full and dequeue is withholding
|
|
|
|
func queue(op dOp) {
|
|
|
|
select {
|
|
|
|
case msgbuf <- op:
|
|
|
|
queueSync.Add(1)
|
|
|
|
default:
|
|
|
|
// send the op anyway if not withholding
|
|
|
|
// as dequeue will get to it eventually
|
|
|
|
if !wstate.Load() {
|
|
|
|
queueSync.Add(1)
|
|
|
|
msgbuf <- op
|
|
|
|
} else {
|
|
|
|
// increment dropped message count
|
|
|
|
dropped.Add(1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-26 23:09:32 +09:00
|
|
|
type dOp interface{ Do() }
|
|
|
|
|
|
|
|
func Exit(code int) {
|
|
|
|
queueSync.Wait()
|
|
|
|
os.Exit(code)
|
|
|
|
}
|
|
|
|
|
2024-11-16 21:19:45 +09:00
|
|
|
func Suspend() {
|
2024-10-27 01:24:30 +09:00
|
|
|
dequeueOnce.Do(dequeue)
|
2024-10-26 23:09:32 +09:00
|
|
|
if wstate.CompareAndSwap(false, true) {
|
2024-11-16 21:19:45 +09:00
|
|
|
queueSync.Wait()
|
2024-10-26 23:09:32 +09:00
|
|
|
withhold <- struct{}{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func Resume() {
|
2024-10-27 01:24:30 +09:00
|
|
|
dequeueOnce.Do(dequeue)
|
2024-10-26 23:09:32 +09:00
|
|
|
if wstate.CompareAndSwap(true, false) {
|
|
|
|
withhold <- struct{}{}
|
2024-11-04 12:56:19 +09:00
|
|
|
if d := dropped.Swap(0); d != 0 {
|
|
|
|
Printf("dropped %d messages during withhold", d)
|
|
|
|
}
|
2024-10-26 23:09:32 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type dPrint []any
|
|
|
|
|
|
|
|
func (v dPrint) Do() {
|
|
|
|
std.Print(v...)
|
|
|
|
}
|
|
|
|
|
|
|
|
type dPrintf struct {
|
|
|
|
format string
|
|
|
|
v []any
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *dPrintf) Do() {
|
|
|
|
std.Printf(d.format, d.v...)
|
|
|
|
}
|
|
|
|
|
|
|
|
type dPrintln []any
|
|
|
|
|
|
|
|
func (v dPrintln) Do() {
|
|
|
|
std.Println(v...)
|
|
|
|
}
|