--- glib/giowin32.c	Wed Jun  8 13:57:40 2005
+++ glib/giowin32.c.patched	Thu Jun  9 07:54:26 2005
@@ -596,6 +596,12 @@
     g_print ("select_thread %#x: got error, setting data_avail\n",
 	     channel->thread_id);
   SetEvent (channel->data_avail_event);
+
+  /* Resetting channel fields */
+  channel->needs_close = FALSE;
+  channel->revents = 0;
+  channel->thread_id = 0;
+
   g_io_channel_unref ((GIOChannel *)channel);
   UNLOCK (channel->mutex);
 
@@ -727,12 +733,18 @@
   channel->watches = g_slist_remove (channel->watches, watch);
 
   SetEvent (channel->data_avail_noticed_event);
-  if (channel->type == G_IO_WIN32_SOCKET)
+  if (channel->watches == NULL && channel->type == G_IO_WIN32_SOCKET)
   {
     /* Tell select_thread() to exit */
     channel->needs_close = 1;
     /* Wake up select_thread() from its blocking select() */
     send (channel->reset_send, send_buffer, sizeof (send_buffer), 0);
+    /* Wait for select_thread() to terminate */
+    do {
+      UNLOCK (channel->mutex);
+      Sleep(10);  /* sleep 10 ms */
+      LOCK (channel->mutex);
+    } while (channel->thread_id != 0);  
   }
 
   g_io_channel_unref (watch->channel);
