How can the nginx detect the stale event using 'instance'?

김수영 sykim at
Tue Feb 21 23:59:18 UTC 2012

Dear Maxim,

Thanks for your comments.

Could you please explain it more details?

I have only seen the epoll module code not kqueue module. The routine is similar to kqueue.

(ngx_epoll_add_event) = (void *) ((uintptr_t) c | ev->instance);

    instance = (uintptr_t) c & 1;
    if (c->fd == -1 || rev->instance != instance) {...}

I'm wondering who set the instance bit.. I just found in ngx_event_process_init() and ngx_get_connection().

    rev = cycle->read_events;
    for (i = 0; i < cycle->connection_n; i++) {
        rev[i].closed = 1;
        rev[i].instance = 1;
        rev[i].lock = &c[i].lock;
        rev[i].own_lock = &c[i].lock;

    instance = rev->instance;
    ngx_memzero(rev, sizeof(ngx_event_t));
    ngx_memzero(wev, sizeof(ngx_event_t));
    rev->instance = !instance;
    wev->instance = !instance;

BUT, I guess that ngx_event_process_init() may be called once 

and ngx_get_connection() may be called when a new connection is accepted(I'm not sure-_-;).

When ngx_event_process_init() is called, instance bit is 1

and then when a new connection is accepted ngx_get_connection(), instance bit is 0. (next ngx_get_connection() will set the instance bit to 1).

And then what happen? I can't trace how the nginx handle it, anymore..-_-;

Please let me know next scenario..^^

-----Original Message-----
From: nginx-devel-bounces at [mailto:nginx-devel-bounces at] On Behalf Of Maxim Dounin
Sent: Tuesday, February 21, 2012 10:28 PM
To: nginx-devel at
Subject: Re: How can the nginx detect the stale event using 'instance'?


On Tue, Feb 21, 2012 at 06:51:19PM +0900, 김수영 wrote:

> These days, I am studying the nginx source code..
> I think this code is very beautiful, and fully modulized.. BUT so it 
> is difficult to follow the code.-_-;
> BTW, In struct ngx_event_s, there is ‘unsigned instance:1;’..
> I can’t understand how can the nginx detect the stale events using 
> it.-_-;
> Could you please explain the detection mechanism or give me a hint?

The "instance" bit is passed in a event user data to the kernel and when the kernel returns the event it's checked against one recorded in the event structure.  If there is no match - this means the event reported by the kernel is stale (i.e. we've already closed the descriptor in the very same event loop iteration).

See e.g. src/event/modules/ngx_kqueue_module.c for details, in particular ngx_kqueue_set_event() and ngx_kqueue_process_events().

Maxim Dounin

nginx-devel mailing list
nginx-devel at

More information about the nginx-devel mailing list