GThreadPool: allow to wait for finishing tasks nondestructively
Submitted by Yeti
Link to original bug (#390817)
Description
GThreadPool is capable of waiting for all tasks to finish, unfortunately it does this only in g_thread_pool_free() which also destructs the pool. Therefore to block until all tasks are finished one has to
(a) busy-wait on g_thread_pool_unprocessed() with some g_thread_yield() to make it [look] less evil
(b) implement barriers (himself as GLib do not provide barrires) -- this is yet another locking scheme duplicating what GThreadPool can already do -- and implement yet another level of wraping around the task functions to prevent their contamination with threading stuff
(c) use g_thread_pool_free(), giving up recycling -- this seems to degrade performance even I set g_thread_pool_set_max_unused_threads(MAX_POSIBLE_NUMBER_OF_THREADS); g_thread_pool_set_max_idle_time(0); to avoid repeated thread creation and destruction.
Now, I don't quite understand the various flags in GRealThreadPool, but it unfortunately seems the assertion waiting == waiting for destruction is a part of the design, so I can't see a straightforward way to implement separate waiting. The following horrible hack roughly illustrates the functionality sought, hopefully someone with better understanding of GThreadPool can come up with a clean solution.
gboolean g_thread_pool_finish(GThreadPool *pool, GTimeVal *abs_time) { GRealThreadPool *real; gboolean ok;
real = (GRealThreadPool*) pool;
g_return_val_if_fail (real, FALSE);
if (! real->running) return TRUE;
g_async_queue_lock (real->queue);
real->running = FALSE; real->immediate = FALSE; real->waiting = TRUE;
real->cond = g_cond_new ();
ok = TRUE; while (ok && g_async_queue_length_unlocked (real->queue) != -real->num_threads) ok = g_cond_timed_wait (real->cond, _g_async_queue_get_mutex (real->queue), abs_time);
/* Try to clean the mess. */ g_cond_free (real->cond); real->cond = NULL; real->waiting = FALSE; real->running = TRUE;
g_async_queue_unlock (real->queue);
return ok; }
Version: 2.12.x