25 #define DEFAULT_WORKERS 0 33 pthread_mutex_t mutex;
37 static int num_workers;
38 static struct worker *workers;
39 static pthread_cond_t worker_cond;
40 static pthread_mutex_t worker_mutex;
44 static void *worker(
void *arg)
46 struct worker *w = arg;
49 pthread_mutex_lock(&w->mutex);
51 pthread_cond_wait(&w->cond, &w->mutex);
53 (*w->func)(w->closure);
58 pthread_mutex_unlock(&w->mutex);
59 pthread_cond_signal(&w->cond);
60 pthread_cond_signal(&worker_cond);
66 static struct worker *get_worker(
void)
70 for (i = 0; i < num_workers; i++) {
71 struct worker *w = &workers[i];
79 void G_begin_execute(
void (*func)(
void *),
void *closure,
void **ref,
int force)
86 pthread_mutex_lock(&worker_mutex);
88 while (w = get_worker(), force && num_workers > 0 && !w)
89 pthread_cond_wait(&worker_cond, &worker_mutex);
93 pthread_mutex_unlock(&worker_mutex);
98 pthread_mutex_lock(&w->mutex);
100 w->closure = closure;
102 pthread_cond_signal(&w->cond);
103 pthread_mutex_unlock(&w->mutex);
105 pthread_mutex_unlock(&worker_mutex);
110 struct worker *w = *ref;
115 pthread_mutex_lock(&w->mutex);
117 pthread_cond_wait(&w->cond, &w->mutex);
118 pthread_mutex_unlock(&w->mutex);
123 const char *p =
getenv(
"WORKERS");
126 pthread_mutex_init(&worker_mutex,
NULL);
127 pthread_cond_init(&worker_cond,
NULL);
129 num_workers = p ? atoi(p) : DEFAULT_WORKERS;
130 workers =
G_calloc(num_workers,
sizeof(
struct worker));
132 for (i = 0; i < num_workers; i++) {
133 struct worker *w = &workers[i];
134 pthread_mutex_init(&w->mutex,
NULL);
135 pthread_cond_init(&w->cond,
NULL);
136 pthread_create(&w->thread,
NULL, worker, w);
144 for (i = 0; i < num_workers; i++) {
145 struct worker *w = &workers[i];
147 pthread_cancel(w->thread);
150 for (i = 0; i < num_workers; i++) {
151 struct worker *w = &workers[i];
152 pthread_join(w->thread,
NULL);
153 pthread_mutex_destroy(&w->mutex);
154 pthread_cond_destroy(&w->cond);
157 pthread_mutex_destroy(&worker_mutex);
158 pthread_cond_destroy(&worker_cond);
void void void void G_fatal_error(const char *,...) __attribute__((format(printf
void G_end_execute(void **ref)
void G_finish_workers(void)
void G_begin_execute(void(*func)(void *), void *closure, void **ref, int force)
void G_init_workers(void)