Showing results for 
Search instead for 
Did you mean: 

Non-blocking infinite loop

New Contributor
I'm trying to read ticks from the socket in an infinite loop. In order to avoid blocking and to eating up the CPU the loop is running in a separate thread:

#include "k.h"

#include <unistd.h>

#include <pthread.h>

#include <stdlib.h>

#include <stdio.h>

void on_quote()


K x = knk(5, ks((S)"AAPL"), kf(100.0), kf(100.0), ki(100), ki(100));

K ret = k(0, (S)".u.upd", ks((S)"quote"), x, (K)NULL);

if(!ret) printf("Socket broken\n");

if(ret->t==-128) printf("Error: %s\n", ret->s);


void *event_loop(void *args)




        // this would select() from socket





extern "C" K listen(K ignore)


pthread_t thread;

int rc = pthread_create(&thread, NULL, event_loop, NULL);

if(rc) {

krr((S)"Unable to create thread");



R (K)0;


This seems to work alight, but if I subscribe with another client, e.g. q cx.q show I get error message Error: no socket.

Noted that the Bloomberg feed handler utilizes fdevent.h, but since my program should run on OS X as well, this is not an option.

What is the proper way to handle this? I have tried looking at the Reuters feed handler, which uses pthread.h, but I haven't managed to implement it properly.

Many thanks!


New Contributor II
New Contributor II
If you have a socket descriptor, just register it with the sd1 call to have kdb+ monitor the socket in its main loop (it uses select.) Then when the socket is ready for reading, kdb+ will callback your registered function with the socket descriptor as a parameter, and you can then read the socket and invoke your on_quote functionality. 

Works like a charm! Thanks a lot!