blob: 8175a4942891d3d3aab43e7757b0198e30f7c0dd [file] [log] [blame]
Holger Hans Peter Freyther97f66e22010-07-28 03:32:52 +08001/*
2 * (C) 2010 by Holger Hans Peter Freyther <zecke@selfish.org>
3 * (C) 2010 by On-Waves
4 * All Rights Reserved
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 */
21#include <thread.h>
22
23#include <laf0rge1/talloc.h>
24
25#include <sys/types.h>
26#include <sys/socket.h>
27
28#include <string.h>
29#include <unistd.h>
30
31static void *tall_ctx_thr;
32
33static int thread_finish(struct thread_notifier *not)
34{
35 pthread_mutex_destroy(&not->guard);
36 close(not->fd[0]);
37 close(not->fd[1]);
38
39 return 0;
40}
41
42void thread_init(void)
43{
44 tall_ctx_thr = talloc_named_const(NULL, 1, "threads");
45}
46
47struct thread_notifier *thread_notifier_alloc()
48{
49 struct thread_notifier *not = talloc_zero(tall_ctx_thr, struct thread_notifier);
50 if (!not)
51 return NULL;
52
53 if (socketpair(AF_UNIX, SOCK_STREAM, 0, not->fd) == -1) {
54 talloc_free(not);
55 return NULL;
56 }
57
58 if (pthread_mutex_init(&not->guard, NULL) != 0) {
59 close(not->fd[0]);
60 close(not->fd[1]);
61 talloc_free(not);
62 return NULL;
63 }
64
65 not->bfd.fd = not->fd[1];
66 INIT_LLIST_HEAD(&not->__head1);
67 INIT_LLIST_HEAD(&not->__head2);
68 not->main_head = &not->__head1;
69 not->thread_head = &not->__head2;
70 talloc_set_destructor(not, thread_finish);
71 return not;
72}
73
74void thread_safe_add(struct thread_notifier *not, struct llist_head *_new)
75{
76 char c;
77 pthread_mutex_lock(&not->guard);
78
79 llist_add_tail(_new, not->thread_head);
80 if (!not->no_write && write(not->fd[0], &c, sizeof(c)) != 1) {
81 fprintf(stderr, "BAD NEWS. Socket write failed.\n");
82 }
83
84 pthread_mutex_unlock(&not->guard);
85}
86
87void thread_swap(struct thread_notifier *not)
88{
89 pthread_mutex_lock(&not->guard);
90
91 if (not->main_head == &not->__head1) {
92 not->main_head = &not->__head2;
93 not->thread_head = &not->__head1;
94 } else {
95 not->main_head = &not->__head1;
96 not->thread_head = &not->__head2;
97 }
98
99 pthread_mutex_unlock(&not->guard);
100}