Some doc additions
[platform/upstream/glib.git] / gio / gioscheduler.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include <config.h>
24
25 #include "gioscheduler.h"
26
27 #include "gioalias.h"
28
29 /**
30  * SECTION:gioscheduler
31  * @short_description: I/O Scheduler
32  * @include: gio.h
33  * 
34  * Schedules asynchronous I/O operations. #GIOScheduler integrates 
35  * into the main event loop (#GMainLoop) and may use threads if they 
36  * are available.
37  * 
38  * <para id="io-priority"><indexterm><primary>I/O priority</primary></indexterm>
39  * Each I/O operation has a priority, and the scheduler uses the priorities
40  * to determine the order in which operations are executed. They are 
41  * <emphasis>not</emphasis> used to determine system-wide I/O scheduling.
42  * Priorities are integers, with lower numbers indicating higher priority. 
43  * It is recommended to choose priorities between %G_PRIORITY_LOW and 
44  * %G_PRIORITY_HIGH, with %G_PRIORITY_DEFAULT as a default.
45  * </para>
46  **/
47
48 struct _GIOSchedulerJob {
49   GSList *active_link;
50   GIOSchedulerJobFunc job_func;
51   GSourceFunc cancel_func; /* Runs under job map lock */
52   gpointer data;
53   GDestroyNotify destroy_notify;
54
55   gint io_priority;
56   GCancellable *cancellable;
57
58   guint idle_tag;
59 };
60
61 G_LOCK_DEFINE_STATIC(active_jobs);
62 static GSList *active_jobs = NULL;
63
64 static GThreadPool *job_thread_pool = NULL;
65
66 static void io_job_thread (gpointer data,
67                            gpointer user_data);
68
69 static void
70 g_io_job_free (GIOSchedulerJob *job)
71 {
72   if (job->cancellable)
73     g_object_unref (job->cancellable);
74   g_free (job);
75 }
76
77 static gint
78 g_io_job_compare (gconstpointer a,
79                   gconstpointer b,
80                   gpointer      user_data)
81 {
82   const GIOSchedulerJob *aa = a;
83   const GIOSchedulerJob *bb = b;
84
85   /* Cancelled jobs are set prio == -1, so that
86      they are executed as quickly as possible */
87   
88   /* Lower value => higher priority */
89   if (aa->io_priority < bb->io_priority)
90     return -1;
91   if (aa->io_priority == bb->io_priority)
92     return 0;
93   return 1;
94 }
95
96 static gpointer
97 init_scheduler (gpointer arg)
98 {
99   if (job_thread_pool == NULL)
100     {
101       /* TODO: thread_pool_new can fail */
102       job_thread_pool = g_thread_pool_new (io_job_thread,
103                                            NULL,
104                                            10,
105                                            FALSE,
106                                            NULL);
107       if (job_thread_pool != NULL)
108         {
109           g_thread_pool_set_sort_function (job_thread_pool,
110                                            g_io_job_compare,
111                                            NULL);
112           /* Its kinda weird that this is a global setting
113            * instead of per threadpool. However, we really
114            * want to cache some threads, but not keep around
115            * those threads forever. */
116           g_thread_pool_set_max_idle_time (15 * 1000);
117           g_thread_pool_set_max_unused_threads (2);
118         }
119     }
120   return NULL;
121 }
122
123 static void
124 remove_active_job (GIOSchedulerJob *job)
125 {
126   GIOSchedulerJob *other_job;
127   GSList *l;
128   gboolean resort_jobs;
129   
130   G_LOCK (active_jobs);
131   active_jobs = g_slist_delete_link (active_jobs, job->active_link);
132   
133   resort_jobs = FALSE;
134   for (l = active_jobs; l != NULL; l = l->next)
135     {
136       other_job = l->data;
137       if (other_job->io_priority >= 0 &&
138           g_cancellable_is_cancelled (other_job->cancellable))
139         {
140           other_job->io_priority = -1;
141           resort_jobs = TRUE;
142         }
143     }
144   G_UNLOCK (active_jobs);
145   
146   if (resort_jobs &&
147       job_thread_pool != NULL)
148     g_thread_pool_set_sort_function (job_thread_pool,
149                                      g_io_job_compare,
150                                      NULL);
151
152 }
153
154 static void
155 io_job_thread (gpointer data,
156                gpointer user_data)
157 {
158   GIOSchedulerJob *job = data;
159
160   if (job->cancellable)
161     g_cancellable_push_current (job->cancellable);
162   job->job_func (job, job->cancellable, job->data);
163   if (job->cancellable)
164     g_cancellable_pop_current (job->cancellable);
165
166   if (job->destroy_notify)
167     job->destroy_notify (job->data);
168
169   remove_active_job (job);
170   g_io_job_free (job);
171
172 }
173
174 static gboolean
175 run_job_at_idle (gpointer data)
176 {
177   GIOSchedulerJob *job = data;
178
179   if (job->cancellable)
180     g_cancellable_push_current (job->cancellable);
181   
182   job->job_func (job, job->cancellable, job->data);
183   
184   if (job->cancellable)
185     g_cancellable_pop_current (job->cancellable);
186
187   if (job->destroy_notify)
188     job->destroy_notify (job->data);
189
190   remove_active_job (job);
191   g_io_job_free (job);
192
193   return FALSE;
194 }
195
196 /**
197  * g_io_scheduler_push_job:
198  * @job_func: a #GIOSchedulerJobFunc.
199  * @user_data: data to pass to @job_func
200  * @notify: a #GDestroyNotify for @user_data, or %NULL
201  * @io_priority: the <link linkend="gioscheduler">I/O priority</link> 
202  * of the request.
203  * @cancellable: optional #GCancellable object, %NULL to ignore.
204  *
205  * Schedules the I/O job to run. 
206  *
207  * @notify will be called on @user_data after @job_func has returned,
208  * regardless whether the job was cancelled or has run to completion.
209  * 
210  * If @cancellable is not %NULL, it can be used to cancel the I/O job
211  * by calling g_cancellable_cancel() or by calling 
212  * g_io_scheduler_cancel_all_jobs().
213  **/
214 void
215 g_io_scheduler_push_job (GIOSchedulerJobFunc  job_func,
216                          gpointer             user_data,
217                          GDestroyNotify       notify,
218                          gint                 io_priority,
219                          GCancellable        *cancellable)
220 {
221   static GOnce once_init = G_ONCE_INIT;
222   GIOSchedulerJob *job;
223
224   g_return_if_fail (job_func != NULL);
225
226   job = g_new0 (GIOSchedulerJob, 1);
227   job->job_func = job_func;
228   job->data = user_data;
229   job->destroy_notify = notify;
230   job->io_priority = io_priority;
231     
232   if (cancellable)
233     job->cancellable = g_object_ref (cancellable);
234
235   G_LOCK (active_jobs);
236   active_jobs = g_slist_prepend (active_jobs, job);
237   job->active_link = active_jobs;
238   G_UNLOCK (active_jobs);
239
240   if (g_thread_supported())
241     {
242       g_once (&once_init, init_scheduler, NULL);
243       g_thread_pool_push (job_thread_pool, job, NULL);
244     }
245   else
246     {
247       /* Threads not available, instead do the i/o sync inside a
248        * low prio idle handler
249        */
250       job->idle_tag = g_idle_add_full (G_PRIORITY_DEFAULT_IDLE + 1 + io_priority / 10,
251                                        run_job_at_idle,
252                                        job, NULL);
253     }
254 }
255
256 /**
257  * g_io_scheduler_cancel_all_jobs:
258  * 
259  * Cancels all cancellable I/O jobs. 
260  *
261  * A job is cancellable if a #GCancellable was passed into
262  * g_io_scheduler_push_job().
263  **/
264 void
265 g_io_scheduler_cancel_all_jobs (void)
266 {
267   GSList *cancellable_list, *l;
268   
269   G_LOCK (active_jobs);
270   cancellable_list = NULL;
271   for (l = active_jobs; l != NULL; l = l->next)
272     {
273       GIOSchedulerJob *job = l->data;
274       if (job->cancellable)
275         cancellable_list = g_slist_prepend (cancellable_list,
276                                             g_object_ref (job->cancellable));
277     }
278   G_UNLOCK (active_jobs);
279
280   for (l = cancellable_list; l != NULL; l = l->next)
281     {
282       GCancellable *c = l->data;
283       g_cancellable_cancel (c);
284       g_object_unref (c);
285     }
286   g_slist_free (cancellable_list);
287 }
288
289 typedef struct {
290   GSourceFunc func;
291   gboolean ret_val;
292   gpointer data;
293   GDestroyNotify notify;
294
295   GMutex *ack_lock;
296   GCond *ack_condition;
297 } MainLoopProxy;
298
299 static gboolean
300 mainloop_proxy_func (gpointer data)
301 {
302   MainLoopProxy *proxy = data;
303
304   proxy->ret_val = proxy->func (proxy->data);
305
306   if (proxy->notify)
307     proxy->notify (proxy->data);
308   
309   if (proxy->ack_lock)
310     {
311       g_mutex_lock (proxy->ack_lock);
312       g_cond_signal (proxy->ack_condition);
313       g_mutex_unlock (proxy->ack_lock);
314     }
315   
316   return FALSE;
317 }
318
319 static void
320 mainloop_proxy_free (MainLoopProxy *proxy)
321 {
322   if (proxy->ack_lock)
323     {
324       g_mutex_free (proxy->ack_lock);
325       g_cond_free (proxy->ack_condition);
326     }
327   
328   g_free (proxy);
329 }
330
331 /**
332  * g_io_scheduler_job_send_to_mainloop:
333  * @job: a #GIOSchedulerJob
334  * @func: a #GSourceFunc callback that will be called in the main thread
335  * @user_data: data to pass to @func
336  * @notify: a #GDestroyNotify for @user_data, or %NULL
337  * 
338  * Used from an I/O job to send a callback to be run in the 
339  * main loop (main thread), waiting for the result (and thus 
340  * blocking the I/O job).
341  *
342  * Returns: The return value of @func
343  **/
344 gboolean
345 g_io_scheduler_job_send_to_mainloop (GIOSchedulerJob *job,
346                                      GSourceFunc      func,
347                                      gpointer         user_data,
348                                      GDestroyNotify   notify)
349 {
350   GSource *source;
351   MainLoopProxy *proxy;
352   guint id;
353   gboolean ret_val;
354
355   g_return_val_if_fail (job != NULL, FALSE);
356   g_return_val_if_fail (func != NULL, FALSE);
357
358   if (job->idle_tag)
359     {
360       /* We just immediately re-enter in the case of idles (non-threads)
361        * Anything else would just deadlock. If you can't handle this, enable threads.
362        */
363       ret_val = func (user_data);
364       if (notify)
365         notify (user_data);
366       return ret_val;
367     }
368   
369   proxy = g_new0 (MainLoopProxy, 1);
370   proxy->func = func;
371   proxy->data = user_data;
372   proxy->notify = notify;
373   proxy->ack_lock = g_mutex_new ();
374   proxy->ack_condition = g_cond_new ();
375   g_mutex_lock (proxy->ack_lock);
376   
377   source = g_idle_source_new ();
378   g_source_set_priority (source, G_PRIORITY_DEFAULT);
379   g_source_set_callback (source, mainloop_proxy_func, proxy,
380                          NULL);
381
382   id = g_source_attach (source, NULL);
383   g_source_unref (source);
384
385   g_cond_wait (proxy->ack_condition, proxy->ack_lock);
386   g_mutex_unlock (proxy->ack_lock);
387
388   ret_val = proxy->ret_val;
389   mainloop_proxy_free (proxy);
390   
391   return ret_val;
392 }
393
394 /**
395  * g_io_scheduler_job_send_to_mainloop_async:
396  * @job: a #GIOSchedulerJob
397  * @func: a #GSourceFunc callback that will be called in the main thread
398  * @user_data: data to pass to @func
399  * @notify: a #GDestroyNotify for @user_data, or %NULL
400  * 
401  * Used from an I/O job to send a callback to be run asynchronously 
402  * in the main loop (main thread). The callback will be run when the 
403  * main loop is available, but at that time the I/O job might have 
404  * finished. The return value from the callback is ignored.
405  *
406  * Note that if you are passing the @user_data from g_io_scheduler_push_job()
407  * on to this function you have to ensure that it is not freed before
408  * @func is called, either by passing %NULL as @notify to 
409  * g_io_scheduler_push_job() or by using refcounting for @user_data.
410  **/
411 void
412 g_io_scheduler_job_send_to_mainloop_async (GIOSchedulerJob *job,
413                                            GSourceFunc      func,
414                                            gpointer         user_data,
415                                            GDestroyNotify   notify)
416 {
417   GSource *source;
418   MainLoopProxy *proxy;
419   guint id;
420
421   g_return_if_fail (job != NULL);
422   g_return_if_fail (func != NULL);
423
424   if (job->idle_tag)
425     {
426       /* We just immediately re-enter in the case of idles (non-threads)
427        * Anything else would just deadlock. If you can't handle this, enable threads.
428        */
429       func (user_data);
430       if (notify)
431         notify (user_data);
432       return;
433     }
434   
435   proxy = g_new0 (MainLoopProxy, 1);
436   proxy->func = func;
437   proxy->data = user_data;
438   proxy->notify = notify;
439   
440   source = g_idle_source_new ();
441   g_source_set_priority (source, G_PRIORITY_DEFAULT);
442   g_source_set_callback (source, mainloop_proxy_func, proxy,
443                          (GDestroyNotify)mainloop_proxy_free);
444
445   id = g_source_attach (source, NULL);
446   g_source_unref (source);
447 }
448
449
450 #define __G_IO_SCHEDULER_C__
451 #include "gioaliasdef.c"