Skip to content

callback from main thread #3

@whyvn

Description

@whyvn

Sometimes its necessary for the callback function to be called from the main thread. In my situation, i need my callback function to use some OpenGL functions however those are only available to the thread which initialised its context (usually the main thread). This is currently possible by setting a bool flag in context which gets toggled in the callback and read by the main event loop e.g.

fn otherThreadCallback(context: ?*anyopaque, event: Event) void {
    context.? = event == event.modified
}

fn mainThreadCallback(context: ?*anyopaque, event: Event) void {
    context.? = false;
    someOpenGLFunction();
}

pub fn main() {
    var changed = false;
    watcher.setCallback(otherThreadCallback, &changed);

    while(true) {
        if(changed)
            mainThreadCallback(&changed, Event.modified);
    }
} 

however this is pretty tedious and has unnecessary function calls. It would be easier if it were something like

pub fn start(self: *LinuxWatcher, opts: interfaces.Opts) !void {
// ...
self.someModifiedFlag = false;
// ...
    if (self.callback) |callback| {
        callback(self.context, interfaces.Event.modified);
    }
    if(opts.flag) self.someModifiedFlag = true;
// ...
}

pub fn poll(self: *LinuxWatcher) bool { return self.someModifiedFlag; }

// -----------------
// user program
pub fn main() {
    while(true) {
        if(watcher.poll())
            mainThreadCallback(&changed, Event.modified);
    }
}

(but without the race condition of course)

This project exists to support fancy-cat and has limited features.

maybe im overthinking a verbose solution to a trivial issue. id be willing to implement it myself but im assuming, because its not necessary and pretty niche, you probably dont want it(?).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions