C/C++ kqueue: Managing Multiple kevents


Active Member

Reaction score: 22
Messages: 188

I'm trying to learn how to do IO multiplexing using kqueue() in C with multiple threads. While I do have a 'good enough' background in C programming for this task, much of my work for the last several years has been with high level languages. My understanding thus far is that the kevent() system call accepts an array of kevent structures as the eventlist parameter. Usually in the (single thread) examples I've seen, the common approach is to declare a fixed size array, create and add your events to that, then pass it over to the kevent system call.

What I would like to do is have one thread to receive requests to register and unregister events. Then another ( one or multiple?) worker threads for actually registering, watching, and handling. I need to be able to keep track of the events to do something like "I want to unregister event #5" where all I have to reference the event by is an array index number. The other requirement is that I do not know in advance how many events I will be registering.

Hopefully the above makes sense and if so... what is the usual way to approach this?
If it doesn't make sense, then I probably need to rethink what I am doing :p

Bobi B.

Well-Known Member

Reaction score: 197
Messages: 416

kevent(2) syscall can modify and query your kqueue simultaneously, but you're not obliged to do so; you can use separate modification and query calls (depending on changelist/nchanges and eventlist/nevents arguments). Not sure if you should modify and query in the same time from different threads.

Besides you don't unsubscribe by index; read the manpage -- man 2 kqueue.