0mq code reading (2): Notification only when necessary

 The lockless queue used by 0mq has a notification mechanism which IMO is pretty nice.  The writer notifies the reader only if  the reader is sleeping or is going to sleep. The technique is quite simple but mixied with the relatively complicated flush/rollback logic, the technique looks less obvious than it actually is.  I will explain it with a very simple example.

Writer:
new_wptr = wptr + 1;
if (cas (c, wptr, new_wptr) == 0) {
    //c is NULL, which implies reader is sleeping or is going to sleep
    wptr = new_wptr;
    //reader is sleeping or is going to sleep, so it is safe to update c
    c.set(new_wptr);  
    return WAKEUP;
}
//c is new_wptr now
wptr = new_wptr;
return DONOT_WAKEUP;

Reader:
if (cas (c,  rptr, 0) == rptr)
    return SLEEP;
++rptr;
return DONOT_SLEEP;

Advertisements
This entry was posted in 0mq code reading. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s