jobs: Fix callsync hanging
[src/app-framework-binder.git] / src / jobs.c
1 /*
2  * Copyright (C) 2016-2019 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <stdlib.h>
21 #include <stdint.h>
22 #include <unistd.h>
23 #include <signal.h>
24 #include <string.h>
25 #include <time.h>
26 #include <sys/syscall.h>
27 #include <pthread.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <sys/eventfd.h>
31
32 #include <systemd/sd-event.h>
33
34 #include "jobs.h"
35 #include "evmgr.h"
36 #include "sig-monitor.h"
37 #include "verbose.h"
38 #include "systemd.h"
39
40 #define EVENT_TIMEOUT_TOP       ((uint64_t)-1)
41 #define EVENT_TIMEOUT_CHILD     ((uint64_t)10000)
42
43 struct thread;
44
45 /** Internal shortcut for callback */
46 typedef void (*job_cb_t)(int, void*);
47
48 /** Description of a pending job */
49 struct job
50 {
51         struct job *next;    /**< link to the next job enqueued */
52         const void *group;   /**< group of the request */
53         job_cb_t callback;   /**< processing callback */
54         void *arg;           /**< argument */
55         int timeout;         /**< timeout in second for processing the request */
56         unsigned blocked: 1; /**< is an other request blocking this one ? */
57         unsigned dropped: 1; /**< is removed ? */
58 };
59
60 /** Description of threads */
61 struct thread
62 {
63         struct thread *next;   /**< next thread of the list */
64         struct thread *upper;  /**< upper same thread */
65         struct thread *nholder;/**< next holder for evloop */
66         pthread_cond_t *cwhold;/**< condition wait for holding */
67         struct job *job;       /**< currently processed job */
68         pthread_t tid;         /**< the thread id */
69         volatile unsigned stop: 1;      /**< stop requested */
70         volatile unsigned waits: 1;     /**< is waiting? */
71         volatile unsigned leaved: 1;    /**< was leaved? */
72 };
73
74 /**
75  * Description of synchronous callback
76  */
77 struct sync
78 {
79         struct thread thread;   /**< thread loop data */
80         union {
81                 void (*callback)(int, void*);   /**< the synchronous callback */
82                 void (*enter)(int signum, void *closure, struct jobloop *jobloop);
83                                 /**< the entering synchronous routine */
84         };
85         void *arg;              /**< the argument of the callback */
86 };
87
88 /* synchronisation of threads */
89 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
90 static pthread_cond_t  cond = PTHREAD_COND_INITIALIZER;
91
92 /* count allowed, started and running threads */
93 static int allowed = 0; /** allowed count of threads */
94 static int started = 0; /** started count of threads */
95 static int running = 0; /** running count of threads */
96 static int remains = 0; /** allowed count of waiting jobs */
97
98 /* list of threads */
99 static struct thread *threads;
100 static _Thread_local struct thread *current_thread;
101
102 /* queue of pending jobs */
103 static struct job *first_job;
104 static struct job *free_jobs;
105
106 /* event loop */
107 static struct evmgr *evmgr;
108
109 static void (*exit_handler)();
110
111 /**
112  * Create a new job with the given parameters
113  * @param group    the group of the job
114  * @param timeout  the timeout of the job (0 if none)
115  * @param callback the function that achieves the job
116  * @param arg      the argument of the callback
117  * @return the created job unblock or NULL when no more memory
118  */
119 static struct job *job_create(
120                 const void *group,
121                 int timeout,
122                 job_cb_t callback,
123                 void *arg)
124 {
125         struct job *job;
126
127         /* try recyle existing job */
128         job = free_jobs;
129         if (job)
130                 free_jobs = job->next;
131         else {
132                 /* allocation without blocking */
133                 pthread_mutex_unlock(&mutex);
134                 job = malloc(sizeof *job);
135                 pthread_mutex_lock(&mutex);
136                 if (!job) {
137                         ERROR("out of memory");
138                         errno = ENOMEM;
139                         goto end;
140                 }
141         }
142         /* initialises the job */
143         job->group = group;
144         job->timeout = timeout;
145         job->callback = callback;
146         job->arg = arg;
147         job->blocked = 0;
148         job->dropped = 0;
149 end:
150         return job;
151 }
152
153 /**
154  * Adds 'job' at the end of the list of jobs, marking it
155  * as blocked if an other job with the same group is pending.
156  * @param job the job to add
157  */
158 static void job_add(struct job *job)
159 {
160         const void *group;
161         struct job *ijob, **pjob;
162
163         /* prepare to add */
164         group = job->group;
165         job->next = NULL;
166
167         /* search end and blockers */
168         pjob = &first_job;
169         ijob = first_job;
170         while (ijob) {
171                 if (group && ijob->group == group)
172                         job->blocked = 1;
173                 pjob = &ijob->next;
174                 ijob = ijob->next;
175         }
176
177         /* queue the jobs */
178         *pjob = job;
179         remains--;
180 }
181
182 /**
183  * Get the next job to process or NULL if none.
184  * @return the first job that isn't blocked or NULL
185  */
186 static inline struct job *job_get()
187 {
188         struct job *job = first_job;
189         while (job && job->blocked)
190                 job = job->next;
191         if (job)
192                 remains++;
193         return job;
194 }
195
196 /**
197  * Releases the processed 'job': removes it
198  * from the list of jobs and unblock the first
199  * pending job of the same group if any.
200  * @param job the job to release
201  */
202 static inline void job_release(struct job *job)
203 {
204         struct job *ijob, **pjob;
205         const void *group;
206
207         /* first unqueue the job */
208         pjob = &first_job;
209         ijob = first_job;
210         while (ijob != job) {
211                 pjob = &ijob->next;
212                 ijob = ijob->next;
213         }
214         *pjob = job->next;
215
216         /* then unblock jobs of the same group */
217         group = job->group;
218         if (group) {
219                 ijob = job->next;
220                 while (ijob && ijob->group != group)
221                         ijob = ijob->next;
222                 if (ijob)
223                         ijob->blocked = 0;
224         }
225
226         /* recycle the job */
227         job->next = free_jobs;
228         free_jobs = job;
229 }
230
231 /**
232  * Monitored cancel callback for a job.
233  * This function is called by the monitor
234  * to cancel the job when the safe environment
235  * is set.
236  * @param signum 0 on normal flow or the number
237  *               of the signal that interrupted the normal
238  *               flow, isn't used
239  * @param arg    the job to run
240  */
241 __attribute__((unused))
242 static void job_cancel(int signum, void *arg)
243 {
244         struct job *job = arg;
245         job->callback(SIGABRT, job->arg);
246 }
247
248 /**
249  * wakeup the event loop if needed by sending
250  * an event.
251  */
252 static void evloop_wakeup()
253 {
254         if (evmgr)
255                 evmgr_wakeup(evmgr);
256 }
257
258 /**
259  * Release the currently held event loop
260  */
261 static void evloop_release()
262 {
263         struct thread *nh, *ct = current_thread;
264
265         if (ct && evmgr && evmgr_release_if(evmgr, ct)) {
266                 nh = ct->nholder;
267                 ct->nholder = 0;
268                 if (nh) {
269                         evmgr_try_hold(evmgr, nh);
270                         pthread_cond_signal(nh->cwhold);
271                 }
272         }
273 }
274
275 /**
276  * get the eventloop for the current thread
277  */
278 static int evloop_get()
279 {
280         return evmgr && evmgr_try_hold(evmgr, current_thread);
281 }
282
283 /**
284  * acquire the eventloop for the current thread
285  */
286 static void evloop_acquire()
287 {
288         struct thread *pwait, *ct;
289         pthread_cond_t cond;
290
291         /* try to get the evloop */
292         if (!evloop_get()) {
293                 /* failed, init waiting state */
294                 ct = current_thread;
295                 ct->nholder = NULL;
296                 ct->cwhold = &cond;
297                 pthread_cond_init(&cond, NULL);
298
299                 /* queue current thread in holder list */
300                 pwait = evmgr_holder(evmgr);
301                 while (pwait->nholder)
302                         pwait = pwait->nholder;
303                 pwait->nholder = ct;
304
305                 /* wake up the evloop */
306                 evloop_wakeup();
307
308                 /* wait to acquire the evloop */
309                 pthread_cond_wait(&cond, &mutex);
310                 pthread_cond_destroy(&cond);
311         }
312 }
313
314 /**
315  * Enter the thread
316  * @param me the description of the thread to enter
317  */
318 static void thread_enter(volatile struct thread *me)
319 {
320         evloop_release();
321         /* initialize description of itself and link it in the list */
322         me->tid = pthread_self();
323         me->stop = 0;
324         me->waits = 0;
325         me->leaved = 0;
326         me->nholder = 0;
327         me->upper = current_thread;
328         me->next = threads;
329         threads = (struct thread*)me;
330         current_thread = (struct thread*)me;
331 }
332
333 /**
334  * leave the thread
335  * @param me the description of the thread to leave
336  */
337 static void thread_leave()
338 {
339         struct thread **prv, *me;
340
341         /* unlink the current thread and cleanup */
342         me = current_thread;
343         prv = &threads;
344         while (*prv != me)
345                 prv = &(*prv)->next;
346         *prv = me->next;
347
348         current_thread = me->upper;
349 }
350
351 /**
352  * Main processing loop of internal threads with processing jobs.
353  * The loop must be called with the mutex locked
354  * and it returns with the mutex locked.
355  * @param me the description of the thread to use
356  * TODO: how are timeout handled when reentering?
357  */
358 static void thread_run_internal(volatile struct thread *me)
359 {
360         struct job *job;
361
362         /* enter thread */
363         thread_enter(me);
364
365         /* loop until stopped */
366         while (!me->stop) {
367                 /* release the current event loop */
368                 evloop_release();
369
370                 /* get a job */
371                 job = job_get();
372                 if (job) {
373                         /* prepare running the job */
374                         job->blocked = 1; /* mark job as blocked */
375                         me->job = job; /* record the job (only for terminate) */
376
377                         /* run the job */
378                         pthread_mutex_unlock(&mutex);
379                         sig_monitor(job->timeout, job->callback, job->arg);
380                         pthread_mutex_lock(&mutex);
381
382                         /* release the run job */
383                         job_release(job);
384                 /* no job, check event loop wait */
385                 } else if (evloop_get()) {
386                         if (!evmgr_can_run(evmgr)) {
387                                 /* busy ? */
388                                 CRITICAL("Can't enter dispatch while in dispatch!");
389                                 abort();
390                         }
391                         /* run the events */
392                         evmgr_prepare_run(evmgr);
393                         pthread_mutex_unlock(&mutex);
394                         sig_monitor(0, (void(*)(int,void*))evmgr_job_run, evmgr);
395                         pthread_mutex_lock(&mutex);
396                 } else {
397                         /* no job and no event loop */
398                         running--;
399                         if (!running)
400                                 ERROR("Entering job deep sleep! Check your bindings.");
401                         me->waits = 1;
402                         pthread_cond_wait(&cond, &mutex);
403                         me->waits = 0;
404                         running++;
405                 }
406         }
407         /* cleanup */
408         evloop_release();
409         thread_leave();
410 }
411
412 /**
413  * Main processing loop of external threads.
414  * The loop must be called with the mutex locked
415  * and it returns with the mutex locked.
416  * @param me the description of the thread to use
417  */
418 static void thread_run_external(volatile struct thread *me)
419 {
420         /* enter thread */
421         thread_enter(me);
422
423         /* loop until stopped */
424         me->waits = 1;
425         while (!me->stop)
426                 pthread_cond_wait(&cond, &mutex);
427         me->waits = 0;
428         thread_leave();
429 }
430
431 /**
432  * Root for created threads.
433  */
434 static void thread_main()
435 {
436         struct thread me;
437
438         running++;
439         started++;
440         sig_monitor_init_timeouts();
441         thread_run_internal(&me);
442         sig_monitor_clean_timeouts();
443         started--;
444         running--;
445 }
446
447 /**
448  * Entry point for created threads.
449  * @param data not used
450  * @return NULL
451  */
452 static void *thread_starter(void *data)
453 {
454         pthread_mutex_lock(&mutex);
455         thread_main();
456         pthread_mutex_unlock(&mutex);
457         return NULL;
458 }
459
460 /**
461  * Starts a new thread
462  * @return 0 in case of success or -1 in case of error
463  */
464 static int start_one_thread()
465 {
466         pthread_t tid;
467         int rc;
468
469         rc = pthread_create(&tid, NULL, thread_starter, NULL);
470         if (rc != 0) {
471                 /* errno = rc; */
472                 WARNING("not able to start thread: %m");
473                 rc = -1;
474         }
475         return rc;
476 }
477
478 /**
479  * Queues a new asynchronous job represented by 'callback' and 'arg'
480  * for the 'group' and the 'timeout'.
481  * Jobs are queued FIFO and are possibly executed in parallel
482  * concurrently except for job of the same group that are
483  * executed sequentially in FIFO order.
484  * @param group    The group of the job or NULL when no group.
485  * @param timeout  The maximum execution time in seconds of the job
486  *                 or 0 for unlimited time.
487  * @param callback The function to execute for achieving the job.
488  *                 Its first parameter is either 0 on normal flow
489  *                 or the signal number that broke the normal flow.
490  *                 The remaining parameter is the parameter 'arg1'
491  *                 given here.
492  * @param arg      The second argument for 'callback'
493  * @param start    Allow to start a thread if not zero
494  * @return 0 in case of success or -1 in case of error
495  */
496 static int queue_job_internal(
497                 const void *group,
498                 int timeout,
499                 void (*callback)(int, void*),
500                 void *arg,
501                 int start)
502 {
503         struct job *job;
504         int rc, busy;
505
506         /* check availability */
507         if (remains <= 0) {
508                 ERROR("can't process job with threads: too many jobs");
509                 errno = EBUSY;
510                 goto error;
511         }
512
513         /* allocates the job */
514         job = job_create(group, timeout, callback, arg);
515         if (!job)
516                 goto error;
517
518         /* check availability */
519         if (remains <= 0) {
520                 ERROR("can't process job with threads: too many jobs");
521                 errno = EBUSY;
522                 goto error2;
523         }
524
525         /* start a thread if needed */
526         busy = running == started;
527         if (start && busy && started < allowed) {
528                 /* all threads are busy and a new can be started */
529                 rc = start_one_thread();
530                 if (rc < 0 && started == 0) {
531                         ERROR("can't start initial thread: %m");
532                         goto error2;
533                 }
534                 busy = 0;
535         }
536
537         /* queues the job */
538         job_add(job);
539
540         /* wakeup an evloop if needed */
541         if (busy)
542                 evloop_wakeup();
543
544         pthread_cond_signal(&cond);
545         return 0;
546
547 error2:
548         job->next = free_jobs;
549         free_jobs = job;
550 error:
551         return -1;
552 }
553
554 /**
555  * Queues a new asynchronous job represented by 'callback' and 'arg'
556  * for the 'group' and the 'timeout'.
557  * Jobs are queued FIFO and are possibly executed in parallel
558  * concurrently except for job of the same group that are
559  * executed sequentially in FIFO order.
560  * @param group    The group of the job or NULL when no group.
561  * @param timeout  The maximum execution time in seconds of the job
562  *                 or 0 for unlimited time.
563  * @param callback The function to execute for achieving the job.
564  *                 Its first parameter is either 0 on normal flow
565  *                 or the signal number that broke the normal flow.
566  *                 The remaining parameter is the parameter 'arg1'
567  *                 given here.
568  * @param arg      The second argument for 'callback'
569  * @param start    Allow to start a thread if not zero
570  * @return 0 in case of success or -1 in case of error
571  */
572 static int queue_job(
573                 const void *group,
574                 int timeout,
575                 void (*callback)(int, void*),
576                 void *arg,
577                 int start)
578 {
579         int rc;
580
581         pthread_mutex_lock(&mutex);
582         rc = queue_job_internal(group, timeout, callback, arg, start);
583         pthread_mutex_unlock(&mutex);
584         return rc;
585
586 }
587
588 /**
589  * Queues a new asynchronous job represented by 'callback' and 'arg'
590  * for the 'group' and the 'timeout'.
591  * Jobs are queued FIFO and are possibly executed in parallel
592  * concurrently except for job of the same group that are
593  * executed sequentially in FIFO order.
594  * @param group    The group of the job or NULL when no group.
595  * @param timeout  The maximum execution time in seconds of the job
596  *                 or 0 for unlimited time.
597  * @param callback The function to execute for achieving the job.
598  *                 Its first parameter is either 0 on normal flow
599  *                 or the signal number that broke the normal flow.
600  *                 The remaining parameter is the parameter 'arg1'
601  *                 given here.
602  * @param arg      The second argument for 'callback'
603  * @return 0 in case of success or -1 in case of error
604  */
605 int jobs_queue(
606                 const void *group,
607                 int timeout,
608                 void (*callback)(int, void*),
609                 void *arg)
610 {
611         return queue_job(group, timeout, callback, arg, 1);
612 }
613
614 /**
615  * Internal helper function for 'jobs_enter'.
616  * @see jobs_enter, jobs_leave
617  */
618 static void enter_cb(int signum, void *closure)
619 {
620         struct sync *sync = closure;
621         sync->enter(signum, sync->arg, (void*)&sync->thread);
622 }
623
624 /**
625  * Internal helper function for 'jobs_call'.
626  * @see jobs_call
627  */
628 static void call_cb(int signum, void *closure)
629 {
630         struct sync *sync = closure;
631         sync->callback(signum, sync->arg);
632         jobs_leave((void*)&sync->thread);
633 }
634
635 /**
636  * Internal helper for synchronous jobs. It enters
637  * a new thread loop for evaluating the given job
638  * as recorded by the couple 'sync_cb' and 'sync'.
639  * @see jobs_call, jobs_enter, jobs_leave
640  */
641 static int do_sync(
642                 const void *group,
643                 int timeout,
644                 void (*sync_cb)(int signum, void *closure),
645                 struct sync *sync
646 )
647 {
648         int rc;
649
650         pthread_mutex_lock(&mutex);
651
652         rc = queue_job_internal(group, timeout, sync_cb, sync, 1);
653         if (rc == 0) {
654                 /* run until stopped */
655                 if (current_thread)
656                         thread_run_internal(&sync->thread);
657                 else
658                         thread_run_external(&sync->thread);
659                 if (!sync->thread.leaved) {
660                         errno = EINTR;
661                         rc = -1;
662                 }
663         }
664         pthread_mutex_unlock(&mutex);
665         return rc;
666 }
667
668 /**
669  * Enter a synchronisation point: activates the job given by 'callback'
670  * and 'closure' using 'group' and 'timeout' to control sequencing and
671  * execution time.
672  * @param group the group for sequencing jobs
673  * @param timeout the time in seconds allocated to the job
674  * @param callback the callback that will handle the job.
675  *                 it receives 3 parameters: 'signum' that will be 0
676  *                 on normal flow or the catched signal number in case
677  *                 of interrupted flow, the context 'closure' as given and
678  *                 a 'jobloop' reference that must be used when the job is
679  *                 terminated to unlock the current execution flow.
680  * @param closure the argument to the callback
681  * @return 0 on success or -1 in case of error
682  */
683 int jobs_enter(
684                 const void *group,
685                 int timeout,
686                 void (*callback)(int signum, void *closure, struct jobloop *jobloop),
687                 void *closure
688 )
689 {
690         struct sync sync;
691
692         sync.enter = callback;
693         sync.arg = closure;
694         return do_sync(group, timeout, enter_cb, &sync);
695 }
696
697 /**
698  * Unlocks the execution flow designed by 'jobloop'.
699  * @param jobloop indication of the flow to unlock
700  * @return 0 in case of success of -1 on error
701  */
702 int jobs_leave(struct jobloop *jobloop)
703 {
704         struct thread *t;
705
706         pthread_mutex_lock(&mutex);
707         t = threads;
708         while (t && t != (struct thread*)jobloop)
709                 t = t->next;
710         if (!t) {
711                 errno = EINVAL;
712         } else {
713                 t->leaved = 1;
714                 t->stop = 1;
715                 if (t->waits)
716                         pthread_cond_broadcast(&cond);
717                 else
718                         evloop_wakeup();
719         }
720         pthread_mutex_unlock(&mutex);
721         return -!t;
722 }
723
724 /**
725  * Calls synchronously the job represented by 'callback' and 'arg1'
726  * for the 'group' and the 'timeout' and waits for its completion.
727  * @param group    The group of the job or NULL when no group.
728  * @param timeout  The maximum execution time in seconds of the job
729  *                 or 0 for unlimited time.
730  * @param callback The function to execute for achieving the job.
731  *                 Its first parameter is either 0 on normal flow
732  *                 or the signal number that broke the normal flow.
733  *                 The remaining parameter is the parameter 'arg1'
734  *                 given here.
735  * @param arg      The second argument for 'callback'
736  * @return 0 in case of success or -1 in case of error
737  */
738 int jobs_call(
739                 const void *group,
740                 int timeout,
741                 void (*callback)(int, void*),
742                 void *arg)
743 {
744         struct sync sync;
745
746         sync.callback = callback;
747         sync.arg = arg;
748
749         return do_sync(group, timeout, call_cb, &sync);
750 }
751
752 /**
753  * Ensure that the current running thread can control the event loop.
754  */
755 void jobs_acquire_event_manager()
756 {
757         struct thread lt;
758
759         /* ensure an existing thread environment */
760         if (!current_thread) {
761                 memset(&lt, 0, sizeof lt);
762                 current_thread = &lt;
763         }
764
765         /* lock */
766         pthread_mutex_lock(&mutex);
767
768         /* creates the evloop on need */
769         if (!evmgr)
770                 evmgr_create(&evmgr);
771
772         /* acquire the event loop under lock */
773         if (evmgr)
774                 evloop_acquire();
775
776         /* unlock */
777         pthread_mutex_unlock(&mutex);
778
779         /* release the faked thread environment if needed */
780         if (current_thread == &lt) {
781                 /*
782                  * Releasing it is needed because there is no way to guess
783                  * when it has to be released really. But here is where it is
784                  * hazardous: if the caller modifies the eventloop when it
785                  * is waiting, there is no way to make the change effective.
786                  * A workaround to achieve that goal is for the caller to
787                  * require the event loop a second time after having modified it.
788                  */
789                 NOTICE("Requiring event manager/loop from outside of binder's callback is hazardous!");
790                 if (verbose_wants(Log_Level_Info))
791                         sig_monitor_dumpstack();
792                 evloop_release();
793                 current_thread = NULL;
794         }
795 }
796
797 /**
798  * Enter the jobs processing loop.
799  * @param allowed_count Maximum count of thread for jobs including this one
800  * @param start_count   Count of thread to start now, must be lower.
801  * @param waiter_count  Maximum count of jobs that can be waiting.
802  * @param start         The start routine to activate (can't be NULL)
803  * @return 0 in case of success or -1 in case of error.
804  */
805 int jobs_start(int allowed_count, int start_count, int waiter_count, void (*start)(int signum, void* arg), void *arg)
806 {
807         int rc, launched;
808         struct job *job;
809
810         assert(allowed_count >= 1);
811         assert(start_count >= 0);
812         assert(waiter_count > 0);
813         assert(start_count <= allowed_count);
814
815         rc = -1;
816         pthread_mutex_lock(&mutex);
817
818         /* check whether already running */
819         if (current_thread || allowed) {
820                 ERROR("thread already started");
821                 errno = EINVAL;
822                 goto error;
823         }
824
825         /* records the allowed count */
826         allowed = allowed_count;
827         started = 0;
828         running = 0;
829         remains = waiter_count;
830
831         /* start at least one thread: the current one */
832         launched = 1;
833         while (launched < start_count) {
834                 if (start_one_thread() != 0) {
835                         ERROR("Not all threads can be started");
836                         goto error;
837                 }
838                 launched++;
839         }
840
841         /* queue the start job */
842         job = job_create(NULL, 0, start, arg);
843         if (!job)
844                 goto error;
845         job_add(job);
846
847         /* run until end */
848         thread_main();
849         rc = 0;
850 error:
851         pthread_mutex_unlock(&mutex);
852         if (exit_handler)
853                 exit_handler();
854         return rc;
855 }
856
857 /**
858  * Exit jobs threads and call handler if not NULL.
859  */
860 void jobs_exit(void (*handler)())
861 {
862         struct thread *t;
863
864         /* request all threads to stop */
865         pthread_mutex_lock(&mutex);
866
867         /* set the handler */
868         exit_handler = handler;
869
870         /* stops the threads */
871         t = threads;
872         while (t) {
873                 t->stop = 1;
874                 t = t->next;
875         }
876
877         /* wake up the threads */
878         evloop_wakeup();
879         pthread_cond_broadcast(&cond);
880
881         /* leave */
882         pthread_mutex_unlock(&mutex);
883 }