Ho to merge event loops from different projects

234 Views Asked by At

I am using Strophe C library for XMPP messaging and libwebsock to create Websocket server.What I want to do is forward the messages recieved on strophe to the Websocket clients and vice versa. However I dont know how to do this.

Also both strophe and libwebsock needs to run event loops to handle events. How can I run both the loops or mege them into one so as to handle the events from both libraries in the same program?

Thanks in advance. :)

1

There are 1 best solutions below

4
On BEST ANSWER

First of all you need to create 2 threads. Let thread1 be libstrophe's event loop and thread2 be libwebsock's event loop respectively. General idea can be described with the next pseudo-code:

xmpp_message_callback() {
    libwebsock_send_text();
}

thread1() {
    xmpp_run();
}

libwebsock_message_callback() {
    xmpp_send();
}

thread2() {
    libwebsock_wait();
}

main() {
    init_libstrophe()
    init_libwebsock();
    create_thread1();
    create_thread2();
    join_thread1();
    join_thread2();
}

But (!) since libstrophe is not thread-safe you can't call xmpp_send() from the thread2 directly. Instead, I would recommend to make a queue protected with a mutex. So, the above example transforms to:

list  queue;
mutex queue_lock;

xmpp_message_callback() {
    libwebsock_send_text();
}

thread1() {
    while {
        xmpp_run_once();
        mutex_lock(queue_lock);
        while (queue is not empty) {
            stanza = list_pop_front(queue);
            xmpp_send(stanza);
        }
        mutex_unlock(queue_lock);
    }
}

libwebsock_message_callback() {
    mutex_lock(queue_lock);
    list_push(queue, stanza);
    mutex_unlock(queue_lock);
}

thread2() {
    libwebsock_wait();
}