How to update the TextView indefinitely?

,

I’ve got a function that sets some parameters for WindowsAPI structure and then in a do-while loop receives data from a COM port indefinitely (i.e. as long as there is data to be received) and updates the TextView with that data. The program freezes and nothing happens (the TextView does not get updated) when I use this function. I tried to invoke it via g_timeout_add but it didn’t help at all as from what I see the program still waits for the function to return.
How should I approach the problem of constantly updating the TextView and not making the rest of the program freeze?

Hi,

All gtk drawing and events processing is done in a dedicated thread (typically from the GLib mainloop), so if you do blocking I/O operation in that thread then of course the interface will freeze.

The correct way to do this is to:

  • create a new thread (e.g. with GTask)
  • do the blocking read of the COM port from that thread
  • when new data is received, use g_idle_add to send it to the main tread used by gtk
  • update the TextBuffer from the g_idle_add 's callback

There are some interesting docs to read:

1 Like

Thank you, I’ll read about these things and try them out.

I wanted to ask if you meant to read the COM port only once or in the do-while loop, because when I attempt to create a simple thread with an infinite or a very long loop in it the program crashes. If an infinite loop is not supposed to be used in a thread then how should I reinvoke the reading function?

An infinite loop should not be a problem…

Just make sure to never call a gtk function from that thread. If you need to update something in gtk, then call g_idle_add(callback, data), to run a callback asynchronously in gtk’s mainloop context, and update the textview from there. Also make sure you return G_SOURCE_REMOVE from that callback.

1 Like

Or use g_idle_add_once(), which has no return value and it’s guaranteed to be called exactly once.

1 Like

All right, thank you for suggestions. I will try them out.

In case anybody needs a simple task example, see this thread.

1 Like