Re: Still confused on new thread starting idle functions to update UI.



On Tue, 3 Dec 2013 13:15:28 -0800 (PST)
David Buchan <pdbuchan yahoo com> wrote:
[snip]
It is awkward, and probably unnecessary.  Unless you have a very good
reason, that is not the way to do it.  Pass the idle function a string
allocated on the heap, and free it in the idle function when finished
with.  Any other way creates thread dependencies which the message
passing approach you have adopted is intended to avoid.

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

Chris, 

For clarification, if I use strdup() to pass to the idle function a
pointer to a copy of the string, and then have the idle function free
it when finished, is that passing it on the heap?

Simplified rough example:

In main():

char *message
message = (char *) malloc (1024);

for loop {

   Calculate good stuff.

  strcpy (message, "Super duper message.");
  g_idle_add ((GSourceFunc) post_message, strdup (message));

  if (we're done) break;
}

free (message);
return (EXIT_SUCCESS);

And the idle function would free that memory before it stops:

int
post_message (char *message)
{
  GtkTextBuffer *textbuffer;
  GtkTextIter end;

  textbuffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW
(data->textview)); gtk_text_buffer_get_end_iter (textbuffer, &end);
  gtk_text_buffer_insert (textbuffer, &end, data->message, -1);
  gtk_text_view_scroll_to_iter (GTK_TEXT_VIEW (data->textview), &end,
0.0, FALSE, 0, 0);

  // Free memory used for message string.
  free (message);

  return (G_SOURCE_REMOVE);
}

I'm not clear on the exact meaning of "heap". Is that what the above
would do?

Yes, malloc() allocates on the heap, as do most of the glib memory
allocation functions.  For any memory allocation function, make sure
you use the corresponding memory freeing function (for malloc() use
free(), for g_malloc() and cognates (such as g_strdup()) use g_free()
and for g_slice_alloc() and cognates use g_slice_free1() and cognates).

However, you have unnecessary steps in your example.  Pass
g_strdup("Super duper message.") to the data argument of g_idle_add(),
and in the idle handler dispose of it with g_free().  Your intermediate
step using the 'message' variable is pointless.  You might want to read
up on memory allocation in C.  Your post_message() function would also
be more aptly described as receive_message(), but that is just a label.

Chris


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