Re: glib: processing events in multiple threads



On Tue, 30 Apr 2013 12:01:34 +0200
Patrick Ohly <patrick ohly intel com> wrote:
On Tue, 2013-04-30 at 10:44 +0100, jcupitt gmail com wrote:
You can do this very simple and reliably. For example:

worker()
{
  char *str;

  for(;;) {
    str = g_strdup("hello world!\n");
    g_idle_add(from_worker_cb, str);
    sleep(1);
  }
}

gboolean
from_worker(char *str)
{
  update_textview(str);
  g_free(str);
  return FALSE;
}

This is one-way. How about two-way communication between threads?

In this example, the worker thread is sending stuff back to the main
program thread's main loop.  It presumes that the main program thread
has passed the work to the worker beforehand in an appropriate way.
That could be by starting a new thread for it, by pushing it onto a
thread pool, or by giving the worker thread its own main loop and
pushing work to it with an idle source (you can't use g_idle_add() or
g_idle_add_full() for that because those functions do not enable you to
choose your GMainContext, but it is trivial to write you own function
to do this in order to hand work to any thread's main loop).

I have a C++ library which implements all three approaches using
futures, task managers and glib main loops which I can send you an url
for if you are not C++ allergic.  C++ variadic templates make this
particularly straightforward.

Chris




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]