Wake GTK helpers for events instead of polling every millisecond
This commit is contained in:
1 parent
eb9dddbc2b
commit
938847e6ae
12 files changed
+328
-80
No files matched your search
@@ -0,0 +1,37 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// Authors: Storm Dragon, Angus Kola
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include <glib.h>
|
||||
#include <unistd.h>
|
||||
#include "wait.h"
|
||||
|
||||
// One iteration of the default main context that also returns when wakeFd is
|
||||
// readable. GLib's own timeout is honored; timeoutMs, when not negative,
|
||||
// shortens it. Readiness on wakeFd is consumed. Returns -1 if another thread
|
||||
// owns the context.
|
||||
int glibwake_wait(int wakeFd, int timeoutMs) {
|
||||
GMainContext *context = g_main_context_default();
|
||||
if (!g_main_context_acquire(context)) return -1;
|
||||
gint priority = 0;
|
||||
g_main_context_prepare(context, &priority);
|
||||
gint capacity = 16, count = 0, timeout = -1;
|
||||
GPollFD *fds = NULL;
|
||||
for (;;) {
|
||||
fds = g_renew(GPollFD, fds, capacity + 1);
|
||||
count = g_main_context_query(context, priority, &timeout, fds, capacity);
|
||||
if (count <= capacity) break;
|
||||
capacity = count;
|
||||
}
|
||||
if (timeoutMs >= 0) timeout = timeout < 0 ? timeoutMs : MIN(timeout, timeoutMs);
|
||||
fds[count] = (GPollFD){.fd = wakeFd, .events = G_IO_IN | G_IO_HUP | G_IO_ERR};
|
||||
g_poll(fds, count + 1, timeout);
|
||||
if (fds[count].revents != 0) {
|
||||
char buffer[64];
|
||||
while (read(wakeFd, buffer, sizeof buffer) > 0) {}
|
||||
}
|
||||
g_main_context_check(context, priority, fds, count);
|
||||
g_main_context_dispatch(context);
|
||||
g_main_context_release(context);
|
||||
g_free(fds);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// Authors: Storm Dragon, Angus Kola
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef CTHULHU_GLIBWAKE_WAIT_H
|
||||
#define CTHULHU_GLIBWAKE_WAIT_H
|
||||
int glibwake_wait(int wakeFd, int timeoutMs);
|
||||
#endif
|
||||
@@ -0,0 +1,71 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// Authors: Storm Dragon, Angus Kola
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// Package glibwake lets a Go loop that owns the default GLib main context
|
||||
// sleep until GLib has work or another goroutine has news for it, instead of
|
||||
// polling on a short ticker.
|
||||
package glibwake
|
||||
|
||||
/*
|
||||
#cgo pkg-config: glib-2.0
|
||||
#include "wait.h"
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrContextBusy = errors.New("GLib main context is owned by another thread")
|
||||
|
||||
// Loop must be waited on from the OS thread that owns the GTK/GLib context.
|
||||
// Wake may be called from any goroutine, including after Close.
|
||||
type Loop struct {
|
||||
read int
|
||||
write *os.File
|
||||
stopWake func() bool
|
||||
}
|
||||
|
||||
// New returns a Loop that also wakes when ctx ends.
|
||||
func New(ctx context.Context) (*Loop, error) {
|
||||
var pipe [2]int
|
||||
if err := syscall.Pipe2(pipe[:], syscall.O_NONBLOCK|syscall.O_CLOEXEC); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Goroutines blocked on input can outlive the loop. A closed os.File
|
||||
// rejects their late writes instead of reaching a reused descriptor.
|
||||
loop := &Loop{read: pipe[0], write: os.NewFile(uintptr(pipe[1]), "glib-wake")}
|
||||
loop.stopWake = context.AfterFunc(ctx, loop.Wake)
|
||||
return loop, nil
|
||||
}
|
||||
|
||||
// Wake ends the current or next Wait. Call it after publishing the news,
|
||||
// such as after a channel send, so the woken loop can observe it.
|
||||
func (loop *Loop) Wake() {
|
||||
_, _ = loop.write.Write([]byte{0})
|
||||
}
|
||||
|
||||
// Wait dispatches one GLib iteration, sleeping until a source is ready, Wake
|
||||
// is called, or timeout passes. A negative timeout waits without a limit of
|
||||
// its own.
|
||||
func (loop *Loop) Wait(timeout time.Duration) error {
|
||||
milliseconds := -1
|
||||
if timeout >= 0 {
|
||||
milliseconds = int(min((timeout+time.Millisecond-1)/time.Millisecond, 1<<30))
|
||||
}
|
||||
if C.glibwake_wait(C.int(loop.read), C.int(milliseconds)) != 0 {
|
||||
return ErrContextBusy
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (loop *Loop) Close() {
|
||||
loop.stopWake()
|
||||
_ = loop.write.Close()
|
||||
_ = syscall.Close(loop.read)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// Authors: Storm Dragon, Angus Kola
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package glibwake
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWaitEndsOnWakeTimeoutAndCancellation(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
loop, err := New(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer loop.Close()
|
||||
|
||||
start := time.Now()
|
||||
if err := loop.Wait(20 * time.Millisecond); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed < 15*time.Millisecond {
|
||||
t.Fatalf("timeout ended after %v", elapsed)
|
||||
}
|
||||
|
||||
go func() {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
loop.Wake()
|
||||
}()
|
||||
if err := waitWithin(t, loop, 5*time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Earlier wakes are consumed, so an idle wait now blocks until cancel.
|
||||
go func() {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
cancel()
|
||||
}()
|
||||
if err := waitWithin(t, loop, 5*time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWakeAfterCloseIsHarmless(t *testing.T) {
|
||||
loop, err := New(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loop.Close()
|
||||
loop.Wake()
|
||||
}
|
||||
|
||||
// waitWithin waits without a timeout of its own and fails if nothing woke it.
|
||||
func waitWithin(t *testing.T, loop *Loop, limit time.Duration) error {
|
||||
t.Helper()
|
||||
guard := time.AfterFunc(limit, loop.Wake)
|
||||
defer guard.Stop()
|
||||
start := time.Now()
|
||||
err := loop.Wait(-1)
|
||||
if time.Since(start) >= limit {
|
||||
t.Fatal("wait was not woken")
|
||||
}
|
||||
return err
|
||||
}
|
||||
Reference in new issue
Block a user