# pthreads and kqueue in D



## sumo_r (Oct 10, 2013)

I have opened a kqueue() in one thread and called kevent() to blocking  waiting events. In another thread I am posting a user event kevent using the same kqueue handle but the first thread never seems to receive it. (D uses phtreads for threading)

The event created is:


```
kevent_t(64557, EVFILT_USER, EV_ADD | EV_CLEAR | EV_ENABLE | EV_ONESHOT, NOTE_TRIGGER, 0, null);
```
Have I set the event up correctly and if so will this work using kqueues? 



```
import std.concurrency, std.conv, std.stdio;
import core.thread;

version(FreeBSD) {
    private import core.sys.freebsd.sys.event;
    private import core.stdc.errno;
    import core.memory;
    import std.exception;
    
    void main() {
        auto mHandle = kqueue();
        auto submit = cast(shared) {
            Thread.sleep(dur!("seconds")(5));
            auto ev = kevent_t(64557, EVFILT_USER, EV_ADD | EV_CLEAR | EV_ENABLE | EV_ONESHOT, NOTE_TRIGGER, 0, null);
            auto ret = kevent(mHandle, &ev, 1, null, 0, null);
            enforce(ret > -1, "Failed to post event to kqueue: " ~ to!string(ret));
            writeln("Posted event to " ~ to!string(mHandle));
        };
        spawn(&spawner, submit, thisTid);
        kevent_t kEvent;     // event that was triggered
        writeln("Evloop on " ~ to!string(mHandle));
        auto ret = kevent(mHandle, null, 0, &kEvent, 1, null);
        enforce(ret > -1, "Failed to read event from kqueue: " ~ to!string(errno));
        writeln("Read event " ~ to!string(kEvent));
    }
    void spawner(void delegate() dp, Tid ownerThread) {
        try {
            dp();
        } catch(shared Exception exc) {
            ownerThread.send(exc);
        }
    }
}
```


----------



## sumo_r (Oct 11, 2013)

*[Solved] - Trigger even separately*

Appears that the event needs to be triggered separately from the addition. So in the spawned thread:


```
auto ev = kevent_t(64557, EVFILT_USER, EV_ADD | EV_CLEAR | EV_ONESHOT, 0, 0, null);
auto ret = kevent(mHandle, &ev, 1, null, 0, null);
enforce(ret > -1, "Failed to post event to kqueue: " ~ to!string(ret));
auto ev2 = kevent_t(64557, EVFILT_USER, 0, NOTE_TRIGGER, 0, null);           
ret = kevent(mHandle, &ev2, 1, null, 0, null);
enforce(ret > -1, "Failed to trigger event on kqueue: " ~ to!string(ret));
```


----------

