Re: Delay time to spawn new threads?





On Wed, 27 Nov 2013 19:32:26 -0800 (PST)
David Buchan <pdbuchan yahoo com> wrote:
I removed the call to g_thread_init() and it still works fine! Great
catch there.

You can include it with glib >= 2.32 - it is a no-op then.  You should
include it if you want your code to be able to run on earlier as
well as later versions

I had put the cast to GThreadFunc there because otherwise I get the
following error:

callbacks.c: In function ‘on_button1_clicked’:
callbacks.c:3829: warning: passing argument 1 of
‘g_thread_create_full’ from incompatible pointer
type /usr/include/glib-2.0/glib/gthread.h:225: note: expected
‘GThreadFunc’ but argument is of type ‘int (*)(struct MyData *)’

I saw other people on the web do the cast as well to remove that
error. Is there a mistake in how I use g_thread_create()? I'd like to
drop the cast if I can. It seemed strange at the time I put it in.

That's fine.  If you are passing user data then you need to do that.

[snip] 
My newly spawned thread calls a function which starts a messaging
idle-function.

[my main program] ---> [my new thread] ----> [post_message function]
===> [update GUI idle function]

In my new thread, I call:

post_message (text, data);

and that looks like:

// Start an instance of activity_message() idle function.
int
post_message (char *message, MyData *data)
{
  // Allocate memory for string; Idle function will free it.
  data->activity_message = allocate_strmem (TEXTLEN);
  // Copy message.
  strncpy (data->activity_message, message, TEXTLEN - 1);  // Minus 1
for string termination.

  g_idle_add ((GSourceFunc) activity_message, data);
  sleep (1);
  return (EXIT_SUCCESS);
}

// Idle function to add a message to the activity textview
// This idle function returns 0 in order to stop.
int
activity_message (MyData *data)
{
  ...
  Update a textview with our message ...

  return (0)
}

I set it up this way so the GUI can be updated.

The call to sleep() protects me against the situation in which my
thread makes a second call to post_message() when activity_message()
hasn't finished updating the GUI from the first call. 

Is there a way to have my thread call post_message() whenever it
needs to, and have the messages queue-up?

You do not need the call to sleep().  g_idle_add() will queue up events
in the glib main loop's event list.  Any one main loop is single
threaded.

By the way, why not have your idle function return FALSE instead of
EXIT_SUCCESS? Both evaluate to 0, but returning FALSE is clearer.
EXIT_SUCCESS is a macro intended to provide a process return value
indicating successful execution of the whole process.  (And could in
theory, though not in practice, be a value other than 0.)


Chris=======================

That's great Chris. And thank to everybody!

Dave


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