Hi,
I would love to use GSocket in my application. I just wonder why its properties are not thread-safe. Is there a common way to modify GSocket’s properties within UI, whereas the GSocket listens in a different thread?
Just after some research I found GTask but I think it is not what I want. Since I don’t need an async result but rather pass data to the async function. But is definitely a closer look worth
Unless explicitly stated in its documentation, no object in GLib (or GObject or GIO) is thread-safe. This is because making things thread-safe introduces a large synchronisation overhead which most applications don’t need; i.e. it’s inefficient.
The typical way to send messages between threads is to use g_idle_add() to schedule an idle callback function to be invoked by the GMainContext for the thread you want (in this case, the thread which is running the GSocket). There are some relevant articles here:
No. I don’t need g_idle_add(). I have an existing application doing pthread and doing linux sockets. I would love to make my code more portable and not rewrite its design.
I think, I am fine with doing read() and write() on the file descriptor on the socket from g_socket_accept() in its very own threads.
See g_socket_get_fd(). But, it is obviously that I can’t modify directly the socket. So I make use of my message queue.
I don’t understand what you are suggesting, sorry.
If you want to pass messages between threads, GLib provides g_idle_add() for message passing.
If you want to use a GSocket from another thread, it’s probably best to pass messages from one thread to another to trigger property changes on the socket.
Otherwise, you should be able to safely change GSocket properties from another thread if you use a mutex to lock all calls to the g_socket_*() methods from all threads, but that includes all read calls in your worker thread, which would slow things down considerably due to the locking overhead.
You can use g_idle_source_new() and g_timeout_source_new(), and then attach them to your main context. g_idle_add() and g_timeout_add() are simple wrappers for those functions centered around the default main context.