Merge branch '1896-use-after-free-when-calling-g_dbus_connection_flush_sync-in-a-dedicated-thread' into 'master'

Resolve "Use after free when calling g_dbus_connection_flush_sync() in a dedicated thread"

Closes #1896

See merge request GNOME/glib!1158
diff --git a/gio/gdbusprivate.c b/gio/gdbusprivate.c
index 0421ca5..302c30b 100644
--- a/gio/gdbusprivate.c
+++ b/gio/gdbusprivate.c
@@ -408,6 +408,7 @@
   GMutex  mutex;
   GCond   cond;
   guint64 number_to_wait_for;
+  gboolean finished;
   GError *error;
 } FlushData;
 
@@ -1158,6 +1159,7 @@
       f->error = error != NULL ? g_error_copy (error) : NULL;
 
       g_mutex_lock (&f->mutex);
+      f->finished = TRUE;
       g_cond_signal (&f->cond);
       g_mutex_unlock (&f->mutex);
     }
@@ -1787,6 +1789,7 @@
       g_mutex_init (&data->mutex);
       g_cond_init (&data->cond);
       data->number_to_wait_for = worker->write_num_messages_written + pending_writes;
+      data->finished = FALSE;
       g_mutex_lock (&data->mutex);
 
       schedule_writing_unlocked (worker, NULL, data, NULL);
@@ -1796,14 +1799,10 @@
   if (data != NULL)
     {
       /* Wait for flush operations to finish. */
-      g_mutex_lock (&worker->write_lock);
-      while (worker->write_num_messages_flushed < data->number_to_wait_for)
+      while (!data->finished)
         {
-          g_mutex_unlock (&worker->write_lock);
           g_cond_wait (&data->cond, &data->mutex);
-          g_mutex_lock (&worker->write_lock);
         }
-      g_mutex_unlock (&worker->write_lock);
 
       g_mutex_unlock (&data->mutex);
       g_cond_clear (&data->cond);