1 /*****************************************************************************
2 * This file is part of gfxprim library. *
4 * Gfxprim is free software; you can redistribute it and/or *
5 * modify it under the terms of the GNU Lesser General Public *
6 * License as published by the Free Software Foundation; either *
7 * version 2.1 of the License, or (at your option) any later version. *
9 * Gfxprim is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
12 * Lesser General Public License for more details. *
14 * You should have received a copy of the GNU Lesser General Public *
15 * License along with gfxprim; if not, write to the Free Software *
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, *
17 * Boston, MA 02110-1301 USA *
19 * Copyright (C) 2009-2012 Cyril Hrubis <metan@ucw.cz> *
21 *****************************************************************************/
26 #include "GP_Common.h"
29 #include "GP_Threads.h"
31 static unsigned int nr_threads
= 1;
33 unsigned int GP_NrThreads(GP_Size w
, GP_Size h
, GP_ProgressCallback
*callback
)
38 /* Try to override nr_threads from the callback first */
39 if (callback
!= NULL
&& callback
->threads
) {
40 GP_DEBUG(1, "Overriding nr_threads from callback to %i",
42 nr_threads
= callback
->threads
;
44 /* Then try to override it from the enviroment variable */
45 env
= getenv("GP_THREADS");
48 nr_threads
= atoi(env
);
49 GP_DEBUG(1, "Using GP_THREADS=%u from enviroment "
50 "variable", nr_threads
);
54 if (nr_threads
== 0) {
55 count
= sysconf(_SC_NPROCESSORS_ONLN
);
56 GP_DEBUG(1, "Found %i CPUs", count
);
59 GP_DEBUG(1, "Using nr_threads=%i", count
);
62 threads
= GP_MIN(count
, (int)(w
* h
/ 1024) + 1);
64 /* Call to the sysconf may return -1 if unsupported */
68 GP_DEBUG(1, "Max threads %i image size %ux%u runnig %u threads",
69 count
, w
, h
, threads
);
74 void GP_NrThreadsSet(unsigned int nr
)
78 GP_DEBUG(1, "Setting default number of threads to %u", nr
);
81 int GP_ProgressCallbackMP(GP_ProgressCallback
*self
)
83 struct GP_ProgressCallbackMPPriv
*priv
= self
->priv
;
86 * If any thread got non-zero return value from a callback abort all.
91 if (pthread_mutex_trylock(&priv
->mutex
)) {
92 GP_DEBUG(1, "Mutex locked, skipping calllback.");
96 /* Compute max value for the percentage */
97 priv
->orig_callback
->percentage
= GP_MAX(self
->percentage
, priv
->max
);
98 priv
->max
= priv
->orig_callback
->percentage
;
100 /* Call the original callback */
101 int ret
= priv
->orig_callback
->callback(priv
->orig_callback
);
103 /* Turn on abort flag if callback returned nonzero */
107 pthread_mutex_unlock(&priv
->mutex
);